Recursive Functions

In [1]:
# a recursive function to find a sum of a list of numbers

def recursive_sum(mylist):
    
    if len(mylist) == 1: # check base case
        return mylist[0]
    else:
        # recursive case
        return mylist[0]+recursive_sum(mylist[1:])
    
def main():
    num_list = [2,4,6]
    
    sum_num = recursive_sum(num_list)
    
    print('The sum is',sum_num)
    
main()
The sum is 12
In [2]:
# a recursive function to find a maximum or minimum value in the list
def find_max(mylist):
    
    if len(mylist) == 1: # base case
        return mylist[0]
    else:
        # recursive case
        b = find_max(mylist[1:])
        if mylist[0] > b:
            return mylist[0]
        else:
            return b
    
def main():
    num_list = [-1,2,-9,4,3]
    
    max_val = find_max(num_list)
    
    print('The maximum value is',max_val)
    
main()
The maximum value is 4
In [3]:
# a recursive function to find a reverse of a string
def reverse_string(mystr):
    if len(mystr) == 1:
        return mystr
    else:
        #return mystr[-1] + reverse_string(mystr[0:-1])
        return reverse_string(mystr[1:]) + mystr[0]
    
def main():
    mystr = 'abcDEF'
    
    reverse_str = reverse_string(mystr)
    
    print(mystr)
    print(reverse_str)
main()
abcDEF
FEDcba
In [4]:
 
In [ ]: