一系列数字的麻烦

2024-03-29 12:11:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个函数的帮助,这个函数不能决定如何包含一系列的数字。 这是我的函数,我不知道为什么不能正确处理范围内的数字。你知道吗

def word_score(word):
    """ (str) -> int
Return the point value the word earns.

Word length: < 3: 0 points
             3-6: 1 point per character for all characters in word
             7-9: 2 points per character for all characters in word
             10+: 3 points per character for all characters in word

>>> word_score('DRUDGERY')
16
"""
if len(word) < 3:
    return 0
elif len(word) == range(3, 6) :
    return len(word)
elif len(word) == range(7, 9):
    return len(word)* 2
elif len(word) >= 10:
    return len(word) * 3



return word_score

Tags: the函数inforlenreturn数字all
3条回答

你对代码所做的不是检查数字是否在某个范围内,而是检查你的数字是否等于你提供的两个数字之间的一个范围。范围不是用于您描述的用法,而是用于生成要迭代的范围。相反,使用if number >= 3 and number >= 6: print ("Within range")

您不希望使用“in”,因为它检查集合中的每一个数字,如果它与您给出的数字相等,那么这是非常低效的,并且在(O)n时间内操作。你知道吗

您应该使用in运算符,这是您的错误:

num = 4
num == range(3, 6) # false
# it will be true if num = [3, 4, 5]
num in range(3, 6) # true
# it means num is 3 or 4 or 5

range不包括最后一个值。例如,range(0,3)将只产生0、1和2,而不是3。你知道吗

此外,还应该检查len(word)是否在范围内,而不是是否等于范围,因为len(word)是字符串,范围是。。。所以它总是产生False。你知道吗

您的代码应该如下所示:

if len(word) < 3:
    return 0
elif len(word) in range(3, 7) :
    return len(word)
elif len(word) in range(7, 10):
    return len(word)* 2
elif len(word) >= 10:
    return len(word) * 3

如果你想使用范围。你知道吗

相关问题 更多 >