[英]Why does the following python code using max() work one way but not another?
I'm doing the exercism.io python test cases, so I'm a newbie at this language.我正在做 exercism.io python 测试用例,所以我是这门语言的新手。
Is there an issue with passing a function that results in an integer to the max() function?将导致整数的函数传递给 max() 函数是否存在问题?
Python 3蟒蛇 3
This code does not work:此代码不起作用:
The error message is TypeError: 'int' object is not callable,错误消息是 TypeError: 'int' object is not callable,
which is the error message that you get if there are not exactly two parameters to the max function.如果 max 函数的参数不完全是两个,那么您会收到错误消息。
Note: The code fails whether I have the (int) included or excluded in the max function.注意:无论我在 max 函数中包含还是排除了 (int),代码都会失败。
The calculate_single function returns the product of list of integers. calculate_single 函数返回整数列表的乘积。
digits is a list of numeric lists.数字是数字列表的列表。
...
largest = 0
for digitlist in digits:
largest = max((int)(calculate_single(digitlist)),largest)
return largest
def calculate_single (digitlist):
current = 1
for digit in digitlist:
current *= (int)(digit)
return current
This code does work.这段代码确实有效。 I just want to know why the first one didn't work.
我只想知道为什么第一个不起作用。
...
largest = 0
for digitlist in digits:
largest = calculate_single(digitlist,largest)
return largest
def calculate_single (digitlist,largest):
current = 1
for digit in digitlist:
current *= (int)(digit)
return max(current,largest)
I tried two versions of your code and seemed that both were just fine.我尝试了你的代码的两个版本,似乎都很好。 version 1:
版本 1:
def calculate_single(digitlist, largest):
current = 1
for digit in digitlist:
current *= (int)(digit)
return max(current, largest)
def calculate(digits):
largest = 0
for digitlist in digits:
#print (largest)
largest = calculate_single(digitlist, largest)
#print (largest)
return largest
if __name__ == '__main__':
lst = [[2, 5, 7, 4.2, 3], [3.6, 6, 4, 2, 1], [5, 5, 5, 10,10]]
big = calculate(lst)
print(big)
version 2:版本 2:
def calculate_single(digitlist):
current = 1
for digit in digitlist:
current *= (int)(digit)
return current
def calculate(digits):
largest = 0
for digitlist in digits:
#print (largest)
largest = max((calculate_single(digitlist)), largest)
#print (largest)
return largest
if __name__ == '__main__':
lst = [[2, 5, 7, 4.2, 3], [3.6, 6, 4, 2, 1], [5, 5, 5, 10,10]]
#lst = [2, 3, 5, 8]
big = calculate(lst)
print(big)
I think the main thing is that digitlist is a list of numbers and digits is a list of lists.我认为最重要的是 digitlist 是一个数字列表,digits 是一个列表列表。 So a list should be passed on to calculate_single() and a list of lists should be passed on to calculate().
所以一个列表应该传递给calculate_single(),一个列表应该传递给calculate()。 If a list is passed on to calculate() it will raise TypeError.
如果一个列表被传递给calculate(),它会引发TypeError。 In both versions max() seemed good no matter with/out int()
在两个版本中 max() 似乎都不错,无论是否使用 int()
在 python 中转换为int
是通过以下方式完成的: int( )而不是(int)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.