


Почему не сходятся ответы?
Вот такой код:
def average_word_length(filename):
# Write code here
f = open(filename)
s = f.read()
print(s)
punctuation = '!?\'",.'
spisok = []
for char in punctuation:
s = s.replace(char, '')
'''было ранее вместо двух строк выше, но результат тот же
for i in s:
if i in punctuation:
s = s.replace(i, '')'''
spisok1 = s.split()
print(spisok1)
for k in spisok1:
spisok.append(len(k))
return round(sum(spisok) / len(spisok), 2)
При тексте в передаваемом файле:
The quick brown fox jumps over the lazy dog. The dog barks, and the fox runs away.
ответ 3.71, который совпадает с верным
при тексте:
Hello there! How are you today? I hope you're doing well. Let's learn about file handling in Python. File handling is an important topic in programming.
мой ответ 4.62, а правильный 4.29
при тексте:
Programming is fun. You can create all sorts of applications with code. From games to utilities, programming empowers creativity. Don't be afraid to make mistakes and learn!
мой ответ 5.37, а правильный 5.1
само задание:
Write a function named average_word_length which gets a filename as argument and returns the average word length (rounded to two decimal points) in the file.
For example,
If input1.txt contains:
The quick brown fox jumps over the lazy dog. The dog barks, and the fox runs away.
Note: remove any punctuation!
подсказки:
Remove the characters !, ?, ', ", ,, . from the words.
Use round(res, 2) function to round res to two decimal points,
Ты просто вырезаешь знаки препинания, склеивая соседние буквы, поэтому «you’re» превращается в «youre», «let’s» – в «lets» и т.д.; в итоге слов получается меньше, а средняя длина – больше, тогда как проверка считает эти апострофы разделителями и делает из «you’re» два слова («you» и «re»), поэтому нужно не удалять символы, а заменять их на пробелы (text = text.replace(ch, ' ')), тогда количество слов выровняется и средняя длина совпадёт с ожидаемой.
Да, SHI абсолютно прав. Я тут накидал код в 1 строчку на C# - возврашает все парвильно:
public static double AvgWorldLen(string _Phrase) => new string(_Phrase.ToLower().ToCharArray().Select(x => Char.IsLetter(x) || x == ' ' ? x : ' ').ToArray()).Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(x => x.Length).Average();
Нафига так с логикой заморачиваться. Мне интересно почему у тебя всё в строку не пошло при обозначении пунктуации но ладно. Скорее всего где то после за ены пробелы считает
сори бро
Эх я учил раньше пайтон, но уже забыл много чего