Write a function word_permutations_dict() that takes a string as input and returns a dictionary where the keys are every word in the input string, and the values are lists containing strings of every permutation of letters of that word.
I have to use recursion here. Heres my code i have tried to caste my list into a set but get an unhashable list error. Any input would be greatly appreciated.
test_string = 'moths are insect teddy bears'
def word_permutations_dict(input_string):
s2 = input_string.split(' ')
d = {}
v = set()
for w in s2:
listtemp = list(w)
v = perms(len(listtemp), listtemp)
d[w] = v
return d
def perms(start, list1):
if start == 1:
list1.append(list1)
else:
for i in range(start - 1):
perms(start - 1, list1)
if i % 2 == 1:
list1[0], list1[start - 1] = list1[start - 1], list1[0]
else:
list1[i], list1[start - 1] = list1[start - 1], list1[i]
perms(start - 1, list1)
return list1
perms_dict = word_permutations_dict(test_string)
for k, v in perms_dict.items():
print('{} : {} permutations'.format(k, len(v)))
output:
moths : 125 permutations
are : 9 permutations
insect : 726 permutations
teddy : 125 permutations
bears : 125 permutations
expected:
moths : 120 permutations
are : 6 permutations
insect : 720 permutations
teddy : 60 permutations
bears : 120 permutations