Question

PYTHON- create recursive functions for these examples. has to be recursive with base cases and cannot...

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

Homework Answers

Answer #1

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 ;)

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Please create a python module named homework.py and implement the functions outlined below. Below you will...
Please create a python module named homework.py and implement the functions outlined below. Below you will find an explanation for each function you need to implement. When you are done please upload the file homework.py to Grader Than. Please get started as soon as possible on this assignment. This assignment has many problems, it may take you longer than normal to complete this assignment. This assignment is supposed to test you on your understanding of reading and writing to a...
In Python: This will require you to write several functions, and then use them in a...
In Python: This will require you to write several functions, and then use them in a program. Logical Calculator The logical calculator does math, but with logical operators. In logic, we represent a bit with 0 as false and a bit with 1 as true. The logical operators are NOT, AND and OR. Bitwise logical calculations operate on each bit of the input. The NOT operator works on just one three-bit argument. NOT 011 = 100 The AND operator works...
*In Java Please RECURSION Objectives • Learn the basics of recursion – Part II (last week...
*In Java Please RECURSION Objectives • Learn the basics of recursion – Part II (last week was Part I) Submission Guidelines: You will turn in 2 program files (one for each lab problem) Tasks This lab has two parts: 1. Write a recursive method repeatNTimes(String s, int n) that accepts a String and an integer as two parameters and returns a string that is concatenated together n times. (For example, repeatNTimes ("hello", 3) returns "hellohellohello") Write a driver program that...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None:...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None: """This method adds new value to the tree, maintaining BST property. Duplicates must be allowed and placed in the right subtree.""" Example #1: tree = BST() print(tree) tree.add(10) tree.add(15) tree.add(5) print(tree) tree.add(15) tree.add(15) print(tree) tree.add(5) print(tree) Output: TREE in order { } TREE in order { 5, 10, 15 } TREE in order { 5, 10, 15, 15, 15 } TREE in order {...
Python Programming Build a python programming that asks the user for a three-letter substring. The program...
Python Programming Build a python programming that asks the user for a three-letter substring. The program should then proceed to read the file strings.txt. Each line in strings.txt will contain a string. Your program should then test to see how many non-overlapping occurrences of the three-letter substring occur in that string and test whether the string is a palindrome. The program should then proceed to create an output file string_stats.txt, which contains the original data on one line and the...
0. Introduction. In this laboratory assignment, you will write a Python class called Zillion. The class...
0. Introduction. In this laboratory assignment, you will write a Python class called Zillion. The class Zillion implements a decimal counter that allows numbers with an effectively infinite number of digits. Of course the number of digits isn’t really infinite, since it is bounded by the amount of memory in your computer, but it can be very large. 1. Examples. Here are some examples of how your class Zillion must work. I’ll first create an instance of Zillion. The string...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
Task 1: You will modify the add method in the LinkedBag class.Add a second parameter to...
Task 1: You will modify the add method in the LinkedBag class.Add a second parameter to the method header that will be a boolean variable: public boolean add(T newEntry, boolean sorted) The modification to the add method will makeit possible toadd new entriesto the beginning of the list, as it does now, but also to add new entries in sorted order. The sorted parameter if set to false will result in the existing functionality being executed (it will add the...
Use object-oriented programming to write an application for a company that uses a subscription-based business model...
Use object-oriented programming to write an application for a company that uses a subscription-based business model to loan out clothes such as office and party wear to female clients. A subscription costs $69 per 4 weeks. A client can make unlimited loan requests during her subscription, as long as she has no previous loan that has not been returned. There can be only one piece of clothes in each loan request. The chosen piece of clothes takes a day to...
IntNode class I am providing the IntNode class you are required to use. Place this class...
IntNode class I am providing the IntNode class you are required to use. Place this class definition within the IntList.h file exactly as is. Make sure you place it above the definition of your IntList class. Notice that you will not code an implementation file for the IntNode class. The IntNode constructor has been defined inline (within the class declaration). Do not write any other functions for the IntNode class. Use as is. struct IntNode { int data; IntNode *next;...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT