谁能帮助我这些python程序?

时间:2013-10-02 16:31:43

标签: python string list if-statement for-loop

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

我的输出应该是: “长于3的单词的分数,以相同的字母开头和结尾: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)
------------------------------------------------------------------------------------------------

1 个答案:

答案 0 :(得分:2)

由于这是家庭作业,为您编写代码是个坏主意。理想情况下,您需要做的是获取符合条件(您提到的)并将其存储在列表中的单词。然后取出列表的长度。

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