Advertisement
MrPolywhirl

Character Replace Anagrams

Oct 8th, 2014
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. import re
  2.  
  3. ### References
  4. #
  5. # Functions
  6. # ----------------------------------------------------------
  7. # * contains() : http://stackoverflow.com/questions/14411633
  8. # * to_dict()  : http://stackoverflow.com/questions/209840/
  9. # * replace()  : http://stackoverflow.com/questions/6116978/
  10. #
  11. # Dictionary
  12. # ----------------------------------------------------------
  13. # * linux.txt  : http://www.cs.duke.edu/~ola/ap/linuxwords
  14.  
  15. read_dict=lambda f:[x.strip() for x in open(f,'r')]
  16. write_dict=lambda f,l:open(f,'w').write('\n'.join(l))
  17. split=lambda l,d:[x.strip() for x in l.split(d)]
  18. split_list=lambda a:(a[:len(a)/2],a[len(a)/2:])
  19. are_anagrams=lambda one,two:sorted(one.lower())==sorted(two.lower())
  20. contains=lambda s,v:len([e in s for e in v if e in s])>0
  21. to_dict=lambda _from,_to:dict(zip(_from,_to))
  22.  
  23. def replacement_map(ch_from, ch_to, bidirectional=False):
  24.     if (bidirectional):
  25.         return dict(to_dict(ch_from, ch_to).items() \
  26.             + to_dict(ch_to, ch_from).items())
  27.     else:
  28.         return to_dict(ch_from, ch_to)
  29.  
  30. def combos(a,b):
  31.     c,s = a+b,min(len(a),len(b))
  32.     return [''.join([c[int(s*((i/(2**(s-j-1)))%2)+j)] for j in range(s)]) for i in range(2**(s))]
  33.    
  34. def opposites(a,b):
  35.     lists = split_list(combos(a,b))
  36.     return zip(lists[0], lists[1][::-1])
  37.  
  38. def replace(s,f,t,bi=True):
  39.     rep = dict((re.escape(k), v) for k, v in replacement_map(f,t,bi).iteritems())
  40.     pattern = re.compile("|".join(rep.keys()))
  41.     return pattern.sub(lambda m: rep[re.escape(m.group(0))], s)
  42.    
  43. def replace_with(word, a, b):
  44.     for key, val in opposites(a, b):
  45.         if contains(word, key):
  46.             return replace(word, key, val)
  47.     return word
  48.  
  49. def find_anagrams(word):
  50.     chars,is_valid = sorted(word.lower()),lambda a,b:a==sorted(b.lower())
  51.     return filter(lambda i:is_valid(chars,i), read_dict('dictionaries/linux.txt'))
  52.    
  53. if __name__ == '__main__':
  54.     _word,_from,_to = 'throws', 'sw', 'ne'
  55.     #print contains(_word, _to)
  56.     #print replace(_word, _to, _from, False)
  57.     #print replacement_map(_to, _from, True)
  58.     #print combos(_to, _from)
  59.     #print opposites(_to, _from)
  60.    
  61.     print find_anagrams(replace_with(_word, _from, _to)) # ['hornet', 'throne']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement