0

*いくつか間違いがあったため、この質問を編集しています。もう一度お読みください* *

次のような単語で辞書を作成する関数を作成しています。

{'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']}

これは次のようになります。

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

「誕生日」のような単語にはうまく機能しますが、文字が繰り返されると問題が発生します... たとえば、「こんにちは」.

{'h': ['h', 'he', 'he', 'hell', 'hello'], 'hell': ['hell', 'hello'], 'hello': ['hello'], 'he': ['he', 'he', 'hell', 'hello']}

インデックスが原因であることはわかっていますが(pythonは文字が最初に表示されたインデックスを選択します)、解決方法がわかりません。はい、これは私の宿題です。皆さんから学ぼうとしています :)

ありがとうございました!

4

4 に答える 4

1

使用enumerate:

for n, letter in enumerate(word):
    if n==0 or n==1:
        continue
    else:
        lst.append(word[0:n])
于 2012-11-27T15:57:55.023 に答える
1
a = 'birthday'
[a[:i] for i in range(2,len(a)+1)]

与える

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

したがって、関数を単純なものに置き換えることができます:

prefix_dict[word] = [word[:i] for i in range(2,len(word)+1)]
于 2012-11-27T16:03:41.250 に答える
0

変数 a が単純な文字列 (例: "birthday"、"hello") であると仮定すると、次のように使用できます。

for i in range(1,len(a)):
    print a[0:i+1]
于 2012-11-27T16:01:44.460 に答える
0
def add_prefixs(word, prefix_dict):
    prefix_dict[word] = [ word[:n+1] for n in range(1, len(word)) ]

さらに良いことに:

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

したがって、関数を「純粋」に保ちます。

于 2012-11-27T16:07:47.733 に答える