我的问题是: 编写一个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)
------------------------------------------------------------------------------------------------
既然这是家庭作业,那么给你写代码不是个好主意。所以理想情况下,你需要做的是,把符合条件的单词(你提到的)存储在一个列表中。然后计算列表的长度。在
然后,你可以把你找到的单词列表的长度除以字典中的作品数。在
相关问题 更多 >
编程相关推荐