Python检查代码是否有错误

时间:2014-11-02 21:05:01

标签: python python-3.4

我被指派编写一个名为作者函数的程序。我写的其中一个函数似乎在我看来是正确的,但我想知道是否有任何不同的方式编写相同的东西,或者我的函数中是否有任何错误。代码如下。谢谢!

def 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

1 个答案:

答案 0 :(得分: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