What I\'m trying to do is if I have a list like:
[\"lime\", \"mile\", \"liem\", \"tag\", \"gat\", \"goat\", \"math\"]
I want to write a functio
An algorithm to check if two words are anagrams in python.
1) Take two words: e.g.
("mile", "lime")
("tiles", "miles")
2) Make a string array/list:
(['m', 'i', 'l', 'e'], ['l', 'i', 'm', 'e'])
(['t', 'i', 'l','e', 's'], ['m', 'i', 'l', 'e', 's'])
3) Sort arrays
(['e', 'i', 'l', 'm'], ['e', 'i', 'l', 'm'])
(['e', 'i', 'l','s', 't'], ['e', 'i', 'l', 'm', 's'])
4)Check if first_array[i]
== second_array[i]
for 0<=i<=len(first_array)||second_array
5) Conclusion. If 4) is held, return true, else false.
from itertools import combinations
def anagram(w1,w2):
list1 = list(w1)
list2 = list(w2)
list1.sort()
list2.sort()
idx = 0
is_anagram = True
while idx < len(w1) and is_anagram:
if list1[idx]== list2[idx]:
idx += 1
else:
is_anagram = False
return is_anagram
lst_words = ["lime", "mile", "liem", "tag", "gat", "goat", "math"]
lst_anagrams = set()
for i in combinations(lst_words, 2):
if anagram(*i):
lst_anagrams |= set(i)
print list(lst_anagrams)