I'm building a function that builds a dictionary with words, such as:
{'b': ['b', 'bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday'],
'bi': ['bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday'],
'birt': ['birt', 'birth', 'birthd', 'birthda', 'birthday'],
'birthda': ['birthda', 'birthday'],
'birthday': ['birthday'],
'birth': ['birth', 'birthd', 'birthda', 'birthday'],
'birthd': ['birthd', 'birthda', 'birthday'],
'bir': ['bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday']}
This is what it looks like:
def add_prefixs(word, prefix_dict):
lst=[]
for letter in word:
n=word.index(letter)
if n==0:
lst.append(word[0])
else:
lst.append(word[0:n])
lst.append(word)
lst.remove(lst[0])
for elem in lst:
b=lst.index(elem)
prefix_dict[elem]=lst[b:]
return prefix_dict
It works great for words like "birthday", but when I have a letter that repeats itself, I have a problem... for example, "hello".
{'h': ['h', 'he', 'he', 'hell', 'hello'], 'hell': ['hell', 'hello'], 'hello': ['hello'], 'he': ['he', 'he', 'hell', 'hello']}
I know it's because of the index (python chooses the index of the first time the letter appears) but I do not know how to solve it. Yes, this is my homework and I'm really trying to learn from you guys :)