JamCoders

💾 Download

JamCoders Week 2 Day 2 Lecture 1

Gunjan Mansingh

RECURSION

When a function calls itself

Question 1

Write an iterative function that multiplies two given numbers without using the * operator. You can use the addition operator. (Use for or while)

In [10]:
#Iterative Using while loop
def mult(x,y):
    result = 0
    ctr = 0
    while (ctr < y ):
        result = result + x
        ctr = ctr + 1
    return result
In [21]:
mult(4,3)
Out[21]:
12

Question 2

Write a recursive function that multiplies two given numbers.

In [14]:
# Recursive function for multiplying numbers
def mult(x,y):
    if y == 0:
        return 0   #Base Case
    else:
        return x + mult(x, y-1)  #Recursive Case
In [20]:
mult(4,3)
Out[20]:
12

Question 3

Write a recursive function power that takes two parameters and raises the first to the second. For example, power (4,3) is 444

move to powerpoint

In [1]:
# Recursive function for finding power
def power(x,y):
    if y == 0:
        return 1   #BASE CASE
    else:
        return x * power(x, y-1)  #RECURSIVE CASE
In [2]:
power(4,3)
Out[2]:
64
In [15]:
#Write a recursive power using mult
def power_m(x,y):
    if y == 0:
        return 1   #Base Case
    else:
        return mult(x, power_m(x, y-1))  #Recursive Case
In [17]:
power_m(5,3)
Out[17]:
125

Questions???