Skip to content

Instantly share code, notes, and snippets.

@reterVision
Created May 5, 2013 07:56
Show Gist options
  • Save reterVision/5520069 to your computer and use it in GitHub Desktop.
Save reterVision/5520069 to your computer and use it in GitHub Desktop.
Anagram solution in Python.
def get_anagram(big_phrase, phrase):
"""
Get a sub-string from a big phrase which is the anagram
with the other string.
"""
print 'Problem: ', big_phrase, phrase
big_phrase = big_phrase.lower()
phrase = phrase.lower().replace(' ', '')
for i in range(len(big_phrase)):
sub_phrase = big_phrase[i:i + len(phrase)]
if len(sub_phrase) < len(phrase):
return ""
anagram = True
for s in sub_phrase:
if s not in phrase:
anagram = False
break
if anagram and set(sub_phrase) == set(phrase):
return sub_phrase
def get_anagram_sort(big_phrase, phrase):
"""
Get a sub-string from a big phrase which is the anagram
with the other string.
First sort, then compare.
"""
print 'Problem: ', big_phrase, phrase
big_phrase = big_phrase.lower()
phrase = phrase.lower().replace(' ', '')
for i in range(len(big_phrase)):
sub_phrase = big_phrase[i:i + len(phrase)].replace(' ', '')
if len(sub_phrase) < len(phrase):
return ""
sorted_subphrase = ''.join(sorted(sub_phrase))
sorted_phrase = ''.join(sorted(phrase))
if sorted_subphrase == sorted_phrase:
return sub_phrase
if __name__ == "__main__":
print get_anagram_sort("abcdbcsdaqdbahs", "scdcb")
print get_anagram_sort("abarcasergctopcodercccsr", "Drop Cote")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment