Python 3.2 - 将单词转换为小写&具有至少3个字母的单词列表中的回文数量

时间:2013-03-24 07:51:25

标签: python return return-value python-3.2 palindrome

我有一个随机的文字文件,其中一些是回文,有些则不是。其中一些回文长度为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))

3 个答案:

答案 0 :(得分: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))

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

祝你好运!

答案 1 :(得分:0)

您正在循环number_of_words以计算count,但number_of_words已初始化为空列表,之后从未更改,因此循环

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

将完全执行0次

答案 2 :(得分: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()

希望当你在这里查看我们的答案并检查上面的迷你实验时,你将能够让你的代码完成你需要做的事情:)