JamCoders

💾 Download

Week 2 - Day 3, Lecture 1

Recursion

Exercise

Question 1 Sum integers in a list recursively

In [1]:
def sumList(lst):
    if lst == []:
        return 0
    else:
        return lst[0] + sumList(lst[1:])
In [7]:
sumList([1,2,3,4,5,6,7,8,9,10])
Out[7]:
55

Question 2. Write a function called evenList that takes a list, and returns a list of even numbers in it. For simplicity assume that the list contains integers.

In [8]:
def evenList(lst):
    if lst == [ ]:
        return [ ]
    elif lst[0]%2==0:
        return [lst[0]]+evenList(lst[1:])
    else:
        return evenList(lst[1:])
In [9]:
evenList([3,5,6,3,22,45,34])
Out[9]:
[6, 22, 34]

Question 3. Write a function called revList that takes a list, and reverses it.

In [11]:
def revList(lst):
    if lst==[]:
        return []
    else:
        return revList(lst[1:]) + [lst[0]]
In [12]:
revList([3,5,6,3,22,45,34])
Out[12]:
[34, 45, 22, 3, 6, 5, 3]

Question 4. Write a recursive function is_palindrome that returns true if a given string is a palindrome and false otherwise

In [49]:
def is_palindrome(str1):
    if len(str1) == 0 or len(str1) == 1:
        return True
    elif str1[0]!=str1[-1]:
        return False
    else:
        return is_palindrome(str1[1:-1])
In [51]:
is_palindrome("race car")
Out[51]:
True
In [55]:
# remove spaces from a string
def removespaces(str1):
    s = str1.replace(" ", "")
    return s

#a fucntion which removes spaces and then checks if a string is a palindrome
# Print appropriate messgaes when you find a palindrome 
def palindrome(str1):
    str1 = removespaces(str1)
    print(str1)
    if is_palindrome(str1):
        print ("Hey!! we have a palindrome")
    else:
        print ("Sorry we dont have a palindrome")
In [53]:
removespaces("madam im adam")
Out[53]:
'madamimadam'
In [56]:
palindrome("madam im adam")
madamimadam
Hey!! we have a palindrome
In [ ]: