+ 5

# Why 3.2=4??

I try to solve the problem in SoloLearn task "Average word length". My code works for 4 tests, but one test shows the strange result. I use ceil for rounding. It rounds 3.2 to 4. Why? And how to fix it? text=input() from math import ceil dtext=text.split() total=sum(len(words)for words in dtext) average=ceil(total/len(dtext)) print(average) Test should show 3, but it shows 4. That is the problem

12 Answers

+ 4

Татьяна Бузлова
Because ceil round a number upward to its nearest integer.
So here ceil(3.2) will be 4.0

+ 3

Татьяна Бузлова
import re
And use this regular expression to replace other characters
'[^a-zA-Z0-9\n\.]'

+ 3

Татьяна Бузлова
Here is your solution:
import re
from math import ceil
text = input()
dtext = text.split()
#total=sum(len(words)for words in dtext)
total = len(re.sub('[^a-zA-Z0-9\n\.]', '', text))
average = ceil(total / len(dtext))
print(average)

+ 3

Adding to Martin Taylor's answer, in the case of round, it rounds to the nearest even number in the case of tie, which means
round(1.5) -> 2.0 but,
round(2.5) -> 2.0

+ 3

Harsh Kothari
In bankers rounding, mid points are rounded off towards the even number.
but in nearest integer Rounding midpoints are rounded off to the nearest integer.

+ 3

Thanks for everybody, there is so much useful information !

+ 2

you can floor or round 3.2 to get 3.
Rounding means the nearest integer from the number.
Flooring means the greatest integer lesser than or equal to the number.
and ceiling means the smallest integer greater than or equal to the number.
and also, in the case of mid points,
like Round(1.5) here it can either be 1 or 2, since both are equidistant but it will always round up to 2, because 1.5 can always mean 1.5 + infinitely small amount, but never lesser than 1.5

+ 2

Code_bot Infact, it does. The reason it does this is so that when rounding a large array of numbers, it does not shift the result too much.

+ 1

I count only alphabet as I use split().
How can I round 3.2 as we do in mathematics, to get 3?

+ 1

Now I tried round,trunc,floor,ceil. But ceil works better than others.

+ 1

I'm fool((( I use split,but there is a "?" in the problem test.... 🙄
I "T", you were right!

+ 1

Татьяна Бузлова This manual implementation of ceil() might help:
ceil = lambda n: float(n // 1 + (n // 1 < n))
# Hope this helps