-12

我的问题是:编写一个 python 程序来获取单词的一部分(这可以是随机字典中的名称列表),它们都长于三个字母并且以相同的字母开头和结尾?

我的输出应该是:“长于三个并且以相同字母开头和结尾的单词的分数:0.065”

请任何人!帮我解决这个问题,我知道这是一个愚蠢的问题,但我刚开始使用 python。

基于这个给定的程序,我应该解决我的程序。

# Function to determine if a string contains three consecutive double lectures
# It has been switched slightly to use a for loop instead of a while loop.
def three_double(s):
    for i in range(0, len(s)-5):
        if s[i] == s[i+1] and s[i+2] == s[i+3] and s[i+4] == s[i+5]:
            return True
    return False

# Function to apply the three_double test to each string in the words
# list.  It counts the number of results.
def find_three_double(words_list):
    count = 0
    for w in words_list:
        if three_double(w):
            print w
            count = count + 1
    if count == 0:
        print '<None found>'
    else:
        print count, 'found'

########################################################################

#  The if statement here tests to see if this is being run as a
#  program or being imported as a module.  When the value of __name__
#  is "__main__" Python is running this is the "main program".  If
#  this file had been imported as a module then the value of __name__
#  would have been "three_double" and the block of code following the
#  if would not be executed.  This establishes one of the central
#  differences between programs and modules and shows how the same
#  code may be used as a program or as a module.

if __name__ == "__main__":
    # Access the file containing the valid words
    words_file = open('words.txt')

    # Read each word, remove the white space and the \n and append it to the list
    words_list = []
    for w in words_file:
        w = w.strip().strip('\n')
        words_list.append(w)

    # Find the three doubles
    find_three_double(words_list)
------------------------------------------------------------------------------------------------
4

1 回答 1

2

由于这是家庭作业,因此为您编写代码不是一个好主意。因此,理想情况下,您需要做的是获取符合标准(您提到的)的单词并将它们存储在列表中。然后取列表的长度。

之后,您可以将找到的单词列表的长度除以词典中的作品数量。

于 2013-10-02T17:04:21.553 回答