从函数[Python]的三个参数中找出最大的奇数

2024-04-19 00:28:41 发布

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

我需要写一个函数,将打印从三个输入参数最大的奇数。你知道吗

这是我的密码。你知道吗

def oddn(x,y,z):
odd_number_keeper = []
for item in x,y,z:
    global odd_number_keeper
    if item % 2==1:
        odd_number_keeper = [item]
        return max(odd_number_keeper)
    else:
        print 'No odd number is found'

我的密码好像坏了。你知道我怎么修改这个代码吗?你知道吗


Tags: 函数in密码numberfor参数returnif
3条回答

需要做一些改变:

def oddn(x,y,z):
    odd_number_keeper = []
    for item in [x,y,z]:
        if item % 2==1:
            odd_number_keeper.append(item)
    if not odd_number_keeper:
        print 'No odd number is found'
        return
    return max(odd_number_keeper)

迭代值xyz,并将奇数加到odd_number_keeper。如果有任何数字,则返回奇数列表中元素的max()。如果没有奇数,则打印消息并返回(没有结果,因为没有要返回的数字)。你知道吗

您没有从列表中找到最大的奇数,而是找到第一个奇数并返回该奇数。问题在于-

odd_number_keeper = [item]
return max(odd_number_keeper)

首先需要将项附加到列表中,而不是将odd_number_keeper列表中只包含该项。你知道吗

其次,return语句应该位于函数的末尾,而不是for循环的内部。你知道吗

你需要一个类似于-

def oddn(x,y,z):
    odd_number_keeper = []
    for item in x,y,z:
        if item % 2==1:
            odd_number_keeper.append(item)
    return max(odd_number_keeper)

您必须先过滤所有奇数,然后调用max

def oddn(x,y,z):
    odd_numbers = [item for item in (x,y,z) if item%2==1]
    return max(odd_numbers)

或者简而言之:

def oddn(*numbers):
    return max(x for x in numbers if x % 2 == 1)

此外,如果要在出错时打印一些消息,这也不是一个好的做法:

def oddn(*numbers):
    try:
        return max(x for x in numbers if x % 2 == 1)
    except ValueError:
        print 'No odd number is found'
        return None

相关问题 更多 >