Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- ### References
- #
- # Functions
- # ----------------------------------------------------------
- # * contains() : http://stackoverflow.com/questions/14411633
- # * to_dict() : http://stackoverflow.com/questions/209840/
- # * replace() : http://stackoverflow.com/questions/6116978/
- #
- # Dictionary
- # ----------------------------------------------------------
- # * linux.txt : http://www.cs.duke.edu/~ola/ap/linuxwords
- read_dict=lambda f:[x.strip() for x in open(f,'r')]
- write_dict=lambda f,l:open(f,'w').write('\n'.join(l))
- split=lambda l,d:[x.strip() for x in l.split(d)]
- split_list=lambda a:(a[:len(a)/2],a[len(a)/2:])
- are_anagrams=lambda one,two:sorted(one.lower())==sorted(two.lower())
- contains=lambda s,v:len([e in s for e in v if e in s])>0
- to_dict=lambda _from,_to:dict(zip(_from,_to))
- def replacement_map(ch_from, ch_to, bidirectional=False):
- if (bidirectional):
- return dict(to_dict(ch_from, ch_to).items() \
- + to_dict(ch_to, ch_from).items())
- else:
- return to_dict(ch_from, ch_to)
- def combos(a,b):
- c,s = a+b,min(len(a),len(b))
- return [''.join([c[int(s*((i/(2**(s-j-1)))%2)+j)] for j in range(s)]) for i in range(2**(s))]
- def opposites(a,b):
- lists = split_list(combos(a,b))
- return zip(lists[0], lists[1][::-1])
- def replace(s,f,t,bi=True):
- rep = dict((re.escape(k), v) for k, v in replacement_map(f,t,bi).iteritems())
- pattern = re.compile("|".join(rep.keys()))
- return pattern.sub(lambda m: rep[re.escape(m.group(0))], s)
- def replace_with(word, a, b):
- for key, val in opposites(a, b):
- if contains(word, key):
- return replace(word, key, val)
- return word
- def find_anagrams(word):
- chars,is_valid = sorted(word.lower()),lambda a,b:a==sorted(b.lower())
- return filter(lambda i:is_valid(chars,i), read_dict('dictionaries/linux.txt'))
- if __name__ == '__main__':
- _word,_from,_to = 'throws', 'sw', 'ne'
- #print contains(_word, _to)
- #print replace(_word, _to, _from, False)
- #print replacement_map(_to, _from, True)
- #print combos(_to, _from)
- #print opposites(_to, _from)
- print find_anagrams(replace_with(_word, _from, _to)) # ['hornet', 'throne']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement