简体   繁体   中英

Find out the biggest odd number from three arguments in a function [Python]

I need to write a function that will print biggest odd number from three input arguments.

Here is my code.

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'

My codes seem is not working. Any ideas how i can modify this code?

A few changes would be needed:

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)

Iterate over the values x , y and z and add the odd numbers to odd_number_keeper . If there are any numbers then you return the max() of the elements in this list of odd numbers. If there are no odd numbers then you print the message and return (without a result, as there is no number to return).

You have to first filter all odd-numbers and then call max :

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

or in short:

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

also it is not good practice, if you want to print some message on error:

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

You are not finding the biggest odd number from the list, instead, you are finding the first odd number and returning that. The issue is in the lines -

odd_number_keeper = [item]
return max(odd_number_keeper)

you first need to be appending item to the list, insteading of making odd_number_keeper the list with only that item.

Secondly, the return statement should be at the end of the function, not inside the for loop.

You need a code something like -

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)

You are resetting odd_number_keeper each time. You probably meant

odd_number_keeper += [item]

Also the return and print should be at the end of (outside) the for loop. (please fix indentation to be clearer on your intent).

Solving it using filter. Doing it in pythonic way.

def oddn(a, b, c):
    final = []
    final.append(a)
    final.append(b)
    final.append(c)
    result = filter(lambda x: x % 2 != 0, final)
    return max(result)

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