Created
May 5, 2017 06:17
-
-
Save lon-io/ae9996e060fe1c6084e375e85bfe40fc to your computer and use it in GitHub Desktop.
Python function to determine if two words are Anagrams of each other
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Determine if an index has been checked | |
def index_not_in(list_of_indices, index): | |
res = True | |
for i in list_of_indices: | |
if index == i: | |
res = False | |
return res | |
# Determine if 2 strings are anagrams | |
def anagram(str1, str2): | |
str1 = str1.lower() | |
str2 = str2.lower() | |
anag = False | |
checked = [] | |
# If the lengths are not equal, return false | |
if len(str1) != len(str2): | |
return False | |
# Check through the 2nd string for unique instances of each item in the first string | |
for index1,i in enumerate(str1): | |
i_present_unique = False | |
for index2, j in enumerate(str2): | |
if str1[index1] == str2[index2] and index_not_in(checked, index2): | |
checked.append(index2) | |
i_present_unique = True | |
break # No point checking the other indices | |
if i_present_unique: | |
anag = True | |
else: | |
anag = False | |
break | |
#print checked | |
return anag | |
print anagram("Orchestra", "Carthorse") | |
print anagram("Debit card", "Bad credit") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment