I did this programming to calculate the average letters of a phrase. Do you think this program is responsible for all texts? And do you have a better offer? Thanks
JavaScript
x
28
28
1
# calculate average word length of phrase
2
3
print("This program will calculate average word length!")
4
5
def length_of_words (string,n):
6
n_words = 0
7
words_in_string=string.split() # Separation of words
8
for this_word in words_in_string: # count the number of letters for each word
9
if len(this_word) == n:
10
n_words = n_words + 1
11
return n_words
12
string = input("Please give me a phrase:n") # get the phrase
13
s = 0 # Initialize the sum
14
iteration = 0 # Initialize to count the number of words
15
for n in range(1,len(string)):
16
len_words=length_of_words(string,n)
17
if len_words==0:
18
continue
19
print("the number of",n, "letter is",len_words)
20
iteration=iteration+1
21
#print(iteration)
22
s=n+s
23
average=s/iteration # average of word length
24
#print(s)
25
print("The average word length of phrase is", average) # Showing average
26
27
28
Advertisement
Answer
Alternatively, this program can be simplified to this function: Your original program just make it overly complex.
JavaScript
1
5
1
def avg_len(sentence):
2
words = sentence.split() # split this sentence to words
3
return sum(len(w) for w in words)/ len(words) # the avg. word's length
4
5
Running it:
JavaScript
1
3
1
>>> avg_len('this is a raining day')
2
3.4
3