I have a base string and a dictionary with certain words. I want to find all the possible anagrams of the base string using the words from the dictionary.
for example:
base_string = 'Oscar Wilde'
words = {1: 'sidecar', 2: 'owl', 3: 'low', 4: 'acid', 5: 'bread', 6: 'slower'}
Now I want to see how many different anagrams I can make with the words from the dictionary. The desired output would be 'sidecar owl', 'sidecar low', 'acid slower'.
I transformed the string into a list, which looks like:
letters = ['o', 's', 'c', 'a', 'r', 'w', 'i', 'l', 'd', 'e']
What I hope my code does is check every combination of words from the dictionary. I have a counter that counts the number of tried combinations.
anagrams = []
counter = 0
for i in range(1, len(words)+1):
anagram = ''
for i in range(i+1, len(words)+1):
if contain(letters, words[i]): #if word is contained in the base string
for i in words[i]: #remove each letter of the word from the list of letters of the base string
letters.remove(i)
anagram += words[i] + ' '
if len(letters) >= 1: #if all the letters are not used, it's not an anagram
counter += 1
if len(letters) == 0: #if all the letters are used, it's an anagram
anagrams.append(anagram)
print anagrams
def contain(list1, list2):
counter1 = Counter(list1)
counter2 = Counter(list2)
for k in counter2:
if counter2[k] != counter1.get(k):
return False
return True
findanagram()
I am getting KeyError for anagram += words[i] + ' '
I hope I've explained myself well enough.