2014-11-02 121 views
-2

我已经被分配去编写一个名为author functions的程序。我写的一个功能在我看来是正确的,但我想知道是否有任何不同的写作方式,或者我的功能有任何错误。代码如下。谢谢!Python检查代码是否有错误

高清CLEAN_UP(S): “””(STR) - > STR

Return a new string based on s in which all letters have been 
converted to lowercase and punctuation characters have been stripped 
from both ends. Inner punctuation is left untouched. 

>>> clean_up('Happy Birthday!!!') 
'happy birthday' 
>>> clean_up("-> It's on your left-hand side.") 
" it's on your left-hand side" 
""" 

punctuation = """!"',;:.-?)([]<>*#\n\t\r""" 
result = s.lower().strip(punctuation) 
return result 
####完成以下功能
def avg_word_length(text): 
    """ (list of str) -> float 

    Precondition: text is non-empty. Each str in text ends with \n and 
    text contains at least one word. 

    Return the average length of all words in text. 

    >>> text = ['James Fennimore Cooper\n', 'Peter, Paul and Mary\n'] 
    >>> avg_word_length(text) 
    5.142857142857143 
    """ 

    # To do: Fill in this function's body to meet its specification. 

    x = '' 
    for i in range(len(text)): 
     x = x + clean_up(text[i]) 
     words = x.split() 
    for word in words: 
     average = sum(len(word) for word in words)/len(words) 
    return average 
+0

是什么'clean_up'? – 2014-11-02 21:09:36

+0

似乎有一些奇怪的事情发生在这里:[还有另一个问题,其中包含此作业的不同版本。](http://stackoverflow.com/questions/26704277/i-have-to-find-the-average-word -长度)。 – Carsten 2014-11-02 21:12:09

+0

哦我道歉它的程序与高清CLEAN_UP(S)开始: “””(STR) - > STR 返回基于在S中的所有字母都被 转换为小写字母和标点符号都被剥夺了一个新的字符串('生日快乐') '生日快乐' >>> clean_up(“ - >它在你的左手边。”) “它在你的左边” “”“ punctuation =”“”!“',;:.-?)([] <> *#\ n \ t \ r”“” result = s.lower()。strip(标点符号) 返回结果 – Ez2Earn 2014-11-02 21:13:18

回答

0

您要加入的最后的,第一句话。每串在一起,你需要让一个空间:

def avg_word_length(text): 
    """ (list of str) -> float 

    Precondition: text is non-empty. Each str in text ends with \n and 
    text contains at least one word. 

    Return the average length of all words in text. 

    5.142857142857143 
    """ 
    cleaned = " ".join([clean_up(w) for w in text]).split() # join using a space between to separate the start and end of the strings 
    return sum(len(w) for w in cleaned)/len(cleaned) 

在您的代码cooperpeter变成一个词让你的计算是关闭

for word in words:是无所事事的sum(len(word) for word in words)有用还遍历的话,当所有的串联通过循环完成,而不是每次你应该分裂:

for i in range(len(text)): 
    x += clean_up(text[i]) 
words = x.split() # outside the loop 
+0

非常感谢你我很感激! – Ez2Earn 2014-11-02 21:59:39

+0

现在担心,不客气。 – 2014-11-02 22:00:40