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

Question:

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.

Asked By: lililllil

||

Answers:

You should implement it like this

def mul(arr):
    if not arr:
        return 1
    return arr[0] * mul(arr[1:])
Answered By: Deepak Tripathi

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)
Answered By: Mulan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.