Home > Blockchain >  In python, how can i get the multiplication of array elements using recursion?
In python, how can i get the multiplication of array elements using recursion?

Time:10-29

I want to get the multiplication of array elements using recursion.

arr is array, and n is length of the array.

if arr=[1, 2, 3], n=3, answer is 6.

I tried this, but error occurred.

def multiply(arr, n):
    if n == 0:
        return arr
    else:
        return arr[n] * \
               multyply(arr[n - 1])

please help me.

CodePudding user response:

You should implement it like this

def mul(arr):
    if not arr:
        return 1
    return arr[0] * mul(arr[1:])

CodePudding user response:

Your approach is close. Try change n to count up and the exit condition to check when n exceeds the length of arr -

def multiply(arr, n = 0):
  if n >= len(arr):
    return 1
  else:
    return arr[n] * multiply(arr, n   1)
  • Related