-1

I am trying to do multiplication recursion (multiplying all the values of a container) in Python. The function receives the elements of the list as positional argument(*n). On execution I receive the error saying "Maximum recursion depth reached". However, the code works fine if I simply use n instead of *n and send the elements in a list.

Code not working:

def multiply(*n):
    if n:       
        return n[0]*multiply(n[1:])
    else:
        return 1

multiply(5,1,4,9)

Working code:

def multiply(n):
    if n:       
        return n[0]*multiply(n[1:])
    else:
        return 1

multiply([5,1,4,9])
Marat
  • 15,215
  • 2
  • 39
  • 48
thunde47
  • 59
  • 5

2 Answers2

0

In the first piece of code, the expression

multiply(n[1:])

is calling multiply with only one argument. Namely, the rest of the list. In order to call it with arguments equal to the contents of the list n[1:], you use the splat operator again, like so:

multiply(*n[1:])

Eli Rose
  • 6,788
  • 8
  • 35
  • 55
0

When you tell a function to expect an arbitrary number of positional arguments with *n, you need to accommodate it in that format: with multiple arguments, not with a single iterable that contains all the arguments. If you have a single iterable whose elements should be used as arguments, you have to unpack it with * when you call it. The second function works because it's expecting a single, iterable argument, and you send it a single, iterable argument.

Replace n[1:] with *n[1:].

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97