1

I would write a recursive function that take a list of number as argument and return maximum element of the list. I don't want to use max() function.

a = [2,1,3,5]
def f(a, m=0):
    if m<a[0]:
        m = a[0]
    if len(a) == 1:
        return m
    else:
        f(a[1:])

print(f(a))

but it returns None! how can I fix it?

1 Answers1

4

You should define m in your else statement and add a return in it:

a = [2,1,3,5]
def f(a, m=0):
    if m<a[0]:
        m = a[0]
    if len(a) == 1:
        return m
    else:
        m = f(a[1:], m)
        return m

print(f(a))
Kasra Najafi
  • 560
  • 5
  • 11
  • 1
    Since the first branch only does what the second branch does as well, it can be eliminated entirely. ``if len(a) > 1: m = f(...)`` followed by an unguarded ``return m`` covers both cases. – MisterMiyagi Jul 13 '20 at 16:02