06. Recursion

Problem

Write a recursive function to obtain length of a given string.

def strlen(t) : 
    if t == '' : 
        return 0
    else : 
        return 1 + strlen(t[1:])

s = input('Enter a string: ')
print(strlen(s))

Interaction

Enter a string: sense
5

Problem

Write a recursive function that reverses a given string.

def strrev(t) : 
    if len(t) == 0 : 
        return t
    else :
        return strrev(t[1:]) + t[0]

s1 = input('Enter a string: ')
s2 = strrev(s1)
print(s2)

Interaction

Enter a string: even
neve

Problem

Write a recursive function that determines whether a given string is a palindrome or not.

def is_palindrome(t) :
    if len(t) < 1 :
        return True
    else :
        if t[0] == t[-1] :
            return is_palindrome(t[1:-1])
        else :
            return False

s = str(input('Enter string: '))
if(is_palindrome(s) == True) :
    print('String is a palindrome')
else:
    print('String is not a palindrome')

Interaction

Enter string: madam
String is a palindrome

Problem

Write a recursive function which flattens a list which may contain several nested lists.

def flatten(l1, l2 = [ ]) :
    for item in l1 :
        if type(item) is not list :
            l2.append(item)
        else :
            flatten(item, l2)

    return l2

lst1 =  [1, [2, [3, 4, [5, 6, [7, 8], [9, [10]], 11], 12], 13], 14, [[15, 16]], 17]    
lst2 = flatten(lst1)
print(lst2)

Interaction

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]

Problem

Define a recursive function that copies source list into a target list and returns the target list.

def copy_list(l1, l2 = [ ]) :
    if len(l1) == 0 :
        return(l2)
    else :
        l2.append(l1[0])
        copy_list(l1[1:], l2)

    return l2

lst1 =  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lst2 = copy_list(lst1)
print(lst2)

Interaction

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Problem

xyz

Interaction