A.K.B
A.K.B

Reputation: 3

Calling a function recursively in Python by passing a List

I know there are easier ways to create a function which gives you the largest number in a list of numbers but I wanted to use recursion. When I call the function greatest, i get none. For example greatest([1,3,2]) gives me none. If there are only two elements in the list, I get the right answer so I know the problem must be with the function calling itself. Not sure why though.

def compare(a,b):
    if a==b:
        return a
    if a > b:
        return a
    if a < b:
        return b


def greatest(x):
    if len(x)==0:
        return 0
    i=0
    new_list=[]
    while i< len(x):
        if len(x)-i>1:
            c=compare(x[i],x[i+1])
        else:
            c=x[i]
        new_list.append(c)
        i=i+2
    if len(new_list)>1:
        greatest(new_list)
    else:
        return new_list[0]

print greatest([1,3,2])

Upvotes: 0

Views: 785

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

A simple recursion can be like this :

from random import *
def greatest(x,maxx=float("-inf")):
    if len(x)>0:
        if x[0] > maxx:
            maxx=x[0]
        return greatest(x[1:],maxx)
    else:
        return maxx

lis=range(10,50)
shuffle(lis)
print greatest(lis) #prints 49

Upvotes: 1

DSM
DSM

Reputation: 353079

This line:

if len(new_list)>1:
    greatest(new_list) # <- this one here

calls greatest but doesn't do anything with the value it returns. You want

    return greatest(new_list)

After fixing that, your function seems to behave (although I didn't look too closely):

>>> import itertools
>>> for i in range(1, 6):
...     print i, all(max(g) == greatest(g) for g in itertools.product(range(-5, 5), repeat=i))
... 
1 True
2 True
3 True
4 True
5 True

Upvotes: 5

Related Questions