-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

在循环之前,您的代码看起来不错:

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

这里的逻辑有问题。如果您考虑 number_of_words 的数据结构,以及您实际要求 python 与 'number >= 3' 条件进行比较的内容,那么我认为您会很好地解决它。

--- 修改外观:

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

NOTES: count_pali: 统计回文单词的总数 high_score: 统计长度超过 3 个字母的回文总数 len(word): 如果 word 是回文,将测试单词的长度

祝你好运!

于 2013-03-24T08:29:11.083 回答
0

You are looping through number_of_words in order to calculate count, but number_of_words is initialized to an empty list and never changed after that, hence the loop

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

will execute exactly 0 times

于 2013-03-24T10:29:49.380 回答
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 回答