I am new to python and I need to calculate the average number of characters in a single word in a list
using these definitions and an auxiliary function clean_up.
the token is str, which you get from calling the string method, broken into a file string.
a word is a non-empty token from a file that does not completely consist of punctuation marks. find the “words” in the file using str.splitto find the markers, and then remove the punctuation marks from the words using a helper function clean_up.
The offer represents a sequence of characters that ends with (but not including) the symbols !, ?, .or end of the file, eliminating gaps at both ends, and is not empty.
This is my homework question from my computer science class at my college.
cleaning function:
def clean_up(s):
punctuation = """!"',;:.-?)([]<>*#\n\"""
result = s.lower().strip(punctuation)
return result
my code is:
def average_word_length(text):
""" (list of str) -> float
Precondition: text is non-empty. Each str in text ends with \n and at
least one str in text contains more than just \n.
Return the average length of all words in text. Surrounding punctuation
is not counted as part of the words.
>>> text = ['James Fennimore Cooper\n', 'Peter, Paul and Mary\n']
>>> average_word_length(text)
5.142857142857143
"""
for ch in text:
word = ch.split()
clean = clean_up(ch)
average = len(clean) / len(word)
return average
I get 5.0, but I was really confused, some help would be greatly appreciated :) PS I am using python 3
source
share