Home > Blockchain >  How to get max odd number in a list using recursion python?
How to get max odd number in a list using recursion python?

Time:10-29

I want to get the maximum odd number in a list using recursion and without using max() or min() functions.

That's what I wrote so far:

def maxOdd(L):
    if L[1:]:
        #check odd numbers only
        if L[0] % 2 == 1:
            #get largest odd number
            if L[0] > maxOdd(L[1:]):
                return L[0]
            else:
                return maxOdd(L[1:]) 
        else:
            return maxOdd(L[1:])        
    #check if list is empty
    elif not L:
        return None
    else:
        return L[0]

But it doesn't work well and doesn't pass this test:

print('Testing maxOdd()...', end='')
assert(maxOdd([ ]) == None)
assert(maxOdd([ 2, 4, 6 ]) == None) 
assert(maxOdd([ 2, 4, 6, 7 ]) == 7)
assert(maxOdd([ -1, -2, -3 ]) == -1)
assert(maxOdd([ 1,2,3,4,5,6,7,8,9,10,0,0,0,11,12 ]) == 11)
print('Passed!')

Can you help me please? I'm stuck for hours. Thank you!

CodePudding user response:

You should make sure that the first item is odd first before ever returning it; otherwise, with your:

if L[1:]:
    ...
else:
    return L[0]

you are going to return the first item even when it is not odd.

A working example:

def maxOdd(L):
    if L:
        first, *rest = L
        max_rest = maxOdd(rest)
        if first % 2 == 1 and (max_rest is None or first > max_rest):
            return first
        return max_rest

Demo: https://replit.com/@blhsing/DisguisedEveryNotification

CodePudding user response:

The issue is with if L[0] > maxOdd(L[1:]):. Since we are finding max Odd, we need to compare only odd values. So if maxOdd(L[1:]) isn't odd, we need to ignore it.

def maxOdd(L):
    if L[1:]:
        if L[0] % 2 == 1:
            x = maxOdd(L[1:])
            #if x is odd, compare. if not rrturn L[0]
            if x is not None and x%2==1:
                if L[0] > x:
                    return L[0]
                else:
                    return x
            else:
                return L[0]
        else:
            return maxOdd(L[1:])
    elif not L:
        return None
    elif L[0]%2==1:
        return L[0]
    else:
        return None

CodePudding user response:

I know you asked for a way to run recursive but maybe this non recursive solution is interesting too:

def max_odd(find_list):
    return sorted([i for i in find_list if i%2==1])[-1]
print(max_odd([1,2,3,4,5,8,99,9,99,8,77,6,5,44,11]))
>99

Code will raise an IndexError in case no odd number is in the list.

  • Related