简体   繁体   中英

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.
Is there an issue with passing a function that results in an integer to the max() function?

Python 3

This code does not work:
The error message is 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.
Note: The code fails whether I have the (int) included or excluded in the max function.

The calculate_single function returns the product of list of integers.

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:

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:

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. So a list should be passed on to calculate_single() and a list of lists should be passed on to calculate(). If a list is passed on to calculate() it will raise TypeError. In both versions max() seemed good no matter with/out int()

在 python 中转换为int是通过以下方式完成的: int( )而不是(int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM