-3

私は単語のランダムなファイルを持っていますが、それらのいくつかは回文であり、いくつかはそうではありません。これらの回文の中には、3 文字以上の長さのものもあります。それらをどのように数えますか?どうすれば条件が良くなるか悩んでいます。私はただ長くできると思っていましたが、答えとして0を取得し続けています.txtファイルがあるため、これは真実ではありません。私はどこを台無しにしていますか?

number_of_words = []

with open('words.txt') as wordFile:
    for word in wordFile:
       word = word.strip()
       for letter in word:
           letter_lower = letter.lower()

def count_pali(wordFile):
    count_pali = 0
    for word in wordFile:
        word = word.strip()
        if word == word[::-1]:
            count_pali += 1
    return count_pali

print(count_pali)

count = 0
for number in number_of_words:
    if number >= 3:
       count += 1

print("Number of palindromes in the list of words that have at least 3 letters: {}".format(count))
4

3 に答える 3

0

これはあなたの質問に直接答えるものではありませんが、ここで遭遇した問題のいくつかを理解するのに役立つかもしれません. ほとんどの場合、リストに追加する方法を確認できます。できれば、文字列、リスト、および整数の長さの取得の違いを確認できます (これは実際にはできません!)。

以下のコードを実行して、何が起こっているかを調べてください。

def step_forward():
    raw_input('(Press ENTER to continue...)')
    print('\n.\n.\n.')

def experiment():
    """ Run a whole lot experiments to explore the idea of lists and
variables"""

    # create an empty list, test length
    word_list = []
    print('the length of word_list is:  {}'.format(len(word_list)))
    # expect output to be zero

    step_forward()

    # add some words to the list
    print('\nAdding some words...')
    word_list.append('Hello')
    word_list.append('Experimentation')
    word_list.append('Interesting')
    word_list.append('ending')

    # test length of word_list again
    print('\ttesting length again...')
    print('\tthe length of word_list is:  {}'.format(len(word_list)))

    step_forward()

    # print the length of each word in the list
    print('\nget the length of each word...')
    for each_word in word_list:
        print('\t{word} has a length of:  {length}'.format(word=each_word, length=len(each_word)))
        # output:
        #    Hello has a length of:  5
        #    Experimentation has a length of:  15
        #    Interesting has a length of:  11
        #    ending has a length of:  6

    step_forward()

    # set up a couple of counters
    short_word = 0
    long_word = 0

    # test the length of the counters:
    print('\nTrying to get the length of our counter variables...')
    try:
        len(short_word)
        len(long_word)
    except TypeError:
        print('\tERROR:  You can not get the length of an int')
    # you see, you can't get the length of an int
    # but, you can get the length of a word, or string!

    step_forward()

    # we will make some new tests, and some assumptions:
    #     short_word:    a word is short, if it has less than 9 letters
    #     long_word:     a word is long, if it has 9 or more letters

    # this test will count how many short and long words there are
    print('\nHow many short and long words are there?...')
    for each_word in word_list:
        if len(each_word) < 9:
            short_word += 1
        else:
            long_word += 1
    print('\tThere are {short} short words and {long} long words.'.format(short=short_word, long=long_word))

    step_forward()

    # BUT... what if we want to know which are the SHORT words and which are the LONG words?
    short_word = 0
    long_word = 0
    for each_word in word_list:
        if len(each_word) < 9:
            short_word += 1
            print('\t{word} is a SHORT word'.format(word=each_word))
        else:
            long_word += 1
            print('\t{word} is a LONG word'.format(word=each_word))

    step_forward()

    # and lastly, if you need to use the short of long words again, you can
    # create new sublists
    print('\nMaking two new lists...')
    shorts = []
    longs = []
    short_word = 0
    long_word = 0

    for each_word in word_list:
        if len(each_word) < 9:
            short_word += 1
            shorts.append(each_word)
        else:
            long_word += 1
            longs.append(each_word)

    print('short list:  {}'.format(shorts))
    print('long list:  {}'.format(longs))
    # now, the counters short_words and long_words should equal the length of the new lists
    if short_word == len(shorts) and long_word == len(longs):
        print('Hurray, its works!')
    else:
        print('Oh no!')

experiment()

うまくいけば、ここで私たちの回答を見て、上記のミニ実験を調べると、コードで必要なことを実行できるようになるでしょう:)

于 2013-03-25T00:47:10.547 に答える
0

number_of_wordsを計算するためにループしてcountnumber_of_wordsますが、空のリストに初期化され、その後は変更されないため、ループ

for number in number_of_words:
    if number >= 3:
        count += 1

正確に 0 回実行されます

于 2013-03-24T10:29:49.380 に答える
0

あなたのコードはループまで見栄えがします:

for number in number_of_words:
    if number >= 3:
        count += 1

ここでロジックに問題があります。number_of_words のデータ構造と、実際に 'number >= 3' 条件と比較するために python に求めているものについて考えると、うまく解決できると思います。

--- 改訂された外観:

# Getting the words into a list
#    word_file = [word1, word2, word3, ..., wordn]
word_file = open('words.txt').readlines()

# set up counters
count_pali, high_score = 0, 0
# iterate through each word and test it

for word in word_file:

    # strip newline character
    word = word.strip()

    # if word is palindrome
    if word == word[::-1]:
        count_pali += 1

        # if word is palindrome AND word is longer than 3 letters
        if len(word) > 3:
            high_score += 1

print('Number of palindromes in the list of words that have at least 3 letter: {}'.format(high_score))

注: count_pali: 回文である単語の総数をカウントします high_score: 3 文字より長い回文の総数をカウントします len(word): 単語が回文の場合、単語の長さをテストします

幸運を!

于 2013-03-24T08:29:11.083 に答える