How can I write a multiplication table with all the elements in the array in recursive programming?

Viewed 361

I am creating a multiplication table with all the elements in the array such as multiply all the elements(2,3,7,8,10) with first element(2). Then, multiply the new values(4,6,14,16,20) with second element(3) and so on.

I could achieve the result relatively simply with a loop.

def multiplication(arr):
    newArr = arr.copy()
    for j in range(len(arr)):
        newArr= [val*arr[j] for val in newArr]
    return newArr

print(multiplication([2,3,7,8,10]))

But when I try to solve it recursively, I am not able to retain the original elements with multiplied values.

def multiplicationRecursively(arr, index=0):
    if (index >= len(arr)):
        return arr
    arr = [val*arr[index] for val in arr]
    return multiplicationRecursively(arr, index+1)

print(multiplicationRecursively([2,3,7,8,10]))

Am I doing something wrong? I think I need to figure out how to retain the original array to get correct multiplier ? I'm learning the Recursive Programming so I'm not willing to use the probably built-in methods.

3 Answers

This is a bit of a whack answer but I believe the issue is the fact that you are no longer multiplying each value with its original value.

def multiplicationRecursively(arr: list, original = None, i = 0):

    if not original:
        return multiplicationRecursively(arr, arr.copy())

    #  Here is the base case
    if (i == len(arr)):
        return arr

    newArr = [v * original[i] for v in arr]
    
    return multiplicationRecursively(newArr, original, i + 1)


print( multiplicationRecursively( [2, 3, 7, 8, 10] ))

With this method, you will retain your original multiplyers and you'll end up with the same results.

This obviously isn't the best way of writing this as a recursion.

The resulting array is nothing but the multiplication of all elements of the original array with each element of the original array. So we can write a recursion as following :

def multiplicationRecursively(arr, mulitplier, index=1):

if (index <= len(arr) -1):
    mulitplier = mulitplier * arr[index]
    return multiplicationRecursively(arr, mulitplier, index+1)
return [mulitplier*val for val in arr]

print(multiplicationRecursively([2,3,7,8,10], 2))

i fully understand the problem you are facing , use this code and you will get the expected result.

 def multiplication_table(array, index = 0):

    multiplier = array.copy()
    
    if (index >= len(array)): 

     return ("")

    else:
        multipling_number = multiplier[index]
        table =[multipling_number*i for i in array]
        print (table, end='\n')

        return multiplication_table(array, index+1)

     Test: 
     array=[1,2,3,4,5]

     print(multiplication_table(array))
     output:
     [1, 2, 3, 4, 5]
     [2, 4, 6, 8, 10]
     [3, 6, 9, 12, 15]
     [4, 8, 12, 16, 20]
     [5, 10, 15, 20, 25]
Related