0

ユーザーに3文字を要求し、次にユーザーに文字列を要求し、文字列内の3文字で始まるすべての単語を出力するプログラムが必要です...例

Enter 3 letters: AMD
Enter text: Advanced Micro Devices is a brand for all microsoft desktops
word: Advanced Micro Devices
word: all microsoft desktops

それはとても簡単です。私は新しく、方法を理解するのに苦労しています...私のコードは現在...

ipt1 = raw_input("Three letters: ") ## Asks for three letters
ipt2 = raw_input("Text: ") ## Asks for text
ipt1_split = ipt1.split() ## Converts three letters to list
ipt2_split = ipt2.split() ## Converts text to list

リストが必要かどうかわかりませんが、この問題に取り組む方法を知っている人はいますか? ありがとう!

4

3 に答える 3

1

いくつかのヒント:

  • 文字列が別の文字列で始まるかどうかをテストするには、 を使用できますstring.startswith()
  • 最初の入力は分割する必要はありません。文字列はシーケンスです。
于 2012-09-06T11:13:11.303 に答える
1

私はこのようなことをします:

letters = raw_input("letters: ").lower()
n = len(letters)
words = raw_input("text: ").split()
words_lc = [x.lower() for x in words] #lowercase copy for case-insensitive check

for x in range(len(words) - n + 1):
    if all((words_lc[x+n].startswith(letters[n]) for n in range(n))):
        print "match: ", ' '.join(words[x:x+n])

この場合、文字数は動的です。3 つに固定したい場合は、3 つに設定nするだけです。文字の大文字と小文字を一致させたい場合はlower、 raw_input の呼び出しと の比較を削除しますall

于 2012-09-06T11:16:37.380 に答える
0

これを試して:

letters = "AMD"
text = "Advanced Micro Devices is a brand for all microsoft desktops"
words = text.split()
for i in xrange(len(words)-len(letters)+1):
    if "".join(map(lambda x: x[0], words[i:i+len(letters)])).lower() == letters.lower():
        print "word:", ".join(words[i:i+len(letters)])
于 2012-09-06T11:53:13.533 に答える