ploffie

is_anagram

Feb 22nd, 2014
69
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from collections import Counter
  2. from itertools import islice, tee
  3.  
  4. def sliding_counter(iterable, window):
  5.     'generates counts for iterable in window, starting at position 0, 1, ...'
  6.     ita, itb = tee(iter(iterable))
  7.     c = Counter(islice(itb, window))
  8.     while 1:
  9.         yield c
  10.         c[next(ita)] -= 1
  11.         c[next(itb)] += 1
  12.        
  13. def is_anagram(first, second):
  14.     'ís a part of the second word an anagram of the first word?'
  15.     target = Counter(first)
  16.     return any(not (a - target) for a in sliding_counter(second, len(first)))
  17.            
  18. print is_anagram("trel", "appletree") # True
  19. print is_anagram("reel", "appletree") # False
  20. print is_anagram("diep", "parallellepipedum") # True
  21. print is_anagram("dier", "parallellepipedum") # False
  22. print is_anagram("pparallelle", "parallellepipedum") # True
  23. print is_anagram(" gnimP", "Programming Praxis") # True
RAW Paste Data