简体   繁体   中英

index of a letter in string - python 2.7

* I'm editing this question because I had a few mistakes, please read again * *

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 :)

Thank you!

Use enumerate :

for n, letter in enumerate(word):
    if n==0 or n==1:
        continue
    else:
        lst.append(word[0:n])
a = 'birthday'
[a[:i] for i in range(2,len(a)+1)]

gives

['bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday']

so you may replace your function with simple:

prefix_dict[word] = [word[:i] for i in range(2,len(word)+1)]

Assuming variable a is a simple string(eg, "birthday", "hello"), you could use:

for i in range(1,len(a)):
    print a[0:i+1]
def add_prefixs(word, prefix_dict):
    prefix_dict[word] = [ word[:n+1] for n in range(1, len(word)) ]

Better yet:

def get_words(word):
    return [ word[:n+1] for n in range(1, len(word)) ]
prefix_dict[word] = get_words(word)

So you keep your function "pure".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM