+ 2
Average Word Length problem
I have a problem with the Code Coach challenge for Average Word Length. This is my code, which is working great for 4/5 tests. Not sure where I'm going wrong. from math import ceil #split input into list avg_string_list = input().split() # list comprehension to get average avg = sum(len(word) for word in avg_string_list)/ len(avg_string_list) #round up floats print(ceil(avg))
10 Respuestas
+ 2
From your point, you not need ceil. Just add floor division.
#split input into list
avg_string_list = input().split()
# list comprehension to get average
avg = sum(len(word) for word in avg_string_list)// len(avg_string_list)
if avg == 3:
print (avg)
else:
print (avg+1)
+ 4
text = input()
z = text.split()
y = len(z)
x = 0
for i in z:
x +=len(i)
print(x/y)
+ 2
xLord , Curtis Dufour Forget it. got my mistake..Was counting punctuations as a character. Remove punctuations from your input string and it will work fine with *ceil* function. Here is my code:
from math import ceil
import string
essay = str(input())
# Remove punctuations from essay string
essay_new = essay.translate(str.maketrans('', '', string.punctuation))
# Split the essay into individual words
words = essay_new.split()
length_each_word = []
for i in range(len(words)):
length_each_word.append(len(words[i]))
total = sum(length_each_word)
average = total/len(length_each_word)
print(ceil(average))
+ 2
text = input()
a=list(text)
y=a.count(" ")
x = y+1
for i in range(y):
a.remove(" ")
b= len(a)
print (b/x)
Is this easy version or hard version
+ 1
xLord ,A little help required. My solution to this problem was very similar to Curtis Dufour except that I didn’t use list comprehensions rather used simple for loop. I was also facing the same problem with “ceil” function and used floor division to complete the test. (thanks to you)
However what I don’t get is ....why did you choose < avg == 3 > as the first condition ... Is it because of the explicit test case that was failing or is there any other reason ...Please explain
What if there was a test case wuth avg value = 4 was present. Would this program still hold good«
0
Thanks! I always forget about floor division and how that works.
0
I answered by his logic. I know is there a better code
0
text = input()
text2 = text.replace(" ", "")
result = len(list(text2))/len(text.split())
print (result)
0
Harshit Sharma thanks for the code! I was desperately trying to write a code like this (there are many complicated versions here) but it seems im not ready yet. Could ANYONE explain this code step by step? That would be sooo helpful :)