Skip to content

Instantly share code, notes, and snippets.

@st0le
Created February 8, 2017 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save st0le/2a3e456abc926324d8160bf1fd9dbd59 to your computer and use it in GitHub Desktop.
Save st0le/2a3e456abc926324d8160bf1fd9dbd59 to your computer and use it in GitHub Desktop.
def find_anagrams(hay, needle):
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
f = lambda c : primes[ord(c.lower()) - ord('a')]
needle_primes = map(f, needle)
needle_primehash = reduce(mul, needle_primes)
current_primehash = 1
l = len(needle)
locations = []
for i,c in enumerate(hay):
if i >= l:
current_primehash //= f(hay[i - l])
current_primehash *= f(c)
if needle_primehash == current_primehash:
locations.append((i - l + 1, hay[i-l+1:i+1]))
return locations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment