我做了这个程序来计算一个短语的平均字母。你认为这个程序是负责所有的文本吗?你有更好的报价吗?谢谢
# calculate average word length of phrase
print("This program will calculate average word length!")
def length_of_words (string,n):
n_words = 0
words_in_string=string.split() # Separation of words
for this_word in words_in_string: # count the number of letters for each word
if len(this_word) == n:
n_words = n_words + 1
return n_words
string = input("Please give me a phrase:\n") # get the phrase
s = 0 # Initialize the sum
iteration = 0 # Initialize to count the number of words
for n in range(1,len(string)):
len_words=length_of_words(string,n)
if len_words==0:
continue
print("the number of",n, "letter is",len_words)
iteration=iteration+1
#print(iteration)
s=n+s
average=s/iteration # average of word length
#print(s)
print("The average word length of phrase is", average) # Showing average
1条答案
按热度按时间w41d8nur1#
或者,该程序可简化为以下函数:你原来的程序只是把它弄得过于复杂。
运行它: