PYTHON- create recursive functions for these examples. has to be recursive with base cases and cannot have loops!
- Return sum of all the #'s inside a certain list. list should not be empty
-if a list contains a certain target return True , False otherwise
- if two strings contain exactly the same chars that are in the same order return True, False otherwise
- if "pre" is a prefix for a string "str", return true and false otherwise
Here is the code for all the four functions usig recursion.
#Example-1
#recursive functin returns sum of elemetns in the passed list parameter
def sum_of_elements(mylist):
# if list is empty , return the 0 value
if(mylist == []):
return 0
#get first item from list
item = mylist[0]
#update the list , by slicing (removing first item)
mylist = mylist[1:]
# recursive call by removing first element and add it with rest of the list's sum
return(item + sum_of_elements(mylist))
#Example-2
#this function returns true, if target is found in the list , otuherwise returns false
def find_target(mylist,target):
#if list becomes empty, it means no target found.
if(mylist==[]):
return False
#pop an item from list,if it is target, return true
item = mylist[0]
mylist = mylist[1:]
if(target==item):
return True
#if poped element is not target, call recursively for rest of the list
else:
return find_target(mylist,target)
#Example-3
#this funciton compare string by each index recursively
def compare(s1, s2):
# base condition, if both strign becomes empty, return true
if(s1 == "" and s2 == ""):
return True
# if both strings has different lengths,they can;t be same.
if(len(s1) != len(s2)):
return False
# if poped elements are same, then call function recursively for rest lists to compare
if(s1[0] == s2[0]):
return compare(s1[1:], s2[1:])
# if none of the case, return false
return False
#Example-4
#this function checks that, if first argument is a prefix for second argument or not.
def checkPrefix(prefix,mystring):
#if pre string becomes empyt, return true
if(prefix==""):
return True
#if mystring is shorter than pre,it mean pre can;t be prefix of mystring
if(mystring=="" and prefix!=""):
return False
#if first indexes, matches of both strings, we call recursively for rest strings
if(prefix[0]==mystring[0]):
return checkPrefix(prefix[1:],mystring[1:])
return False
#testing all funcitons
a = sum_of_elements([1,2,3,-2,4]) #answer should be 8
b = find_target([1,2,6,5,4],6) #answer should be True
c = compare("Nikhil","Nikhik") #anser should be False
d = checkPrefix("nik",'nikfg') #anser should be True
#print all funcitons answers
print(a,b,c,d)
.
output:
Hope It Helps!
Thumbsup ;)
Get Answers For Free
Most questions answered within 1 hours.