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 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...
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;...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g,...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g, char wordlist[][MAX_WORD_LENGTH], int numwords)] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) What int setup_game needs to do setup_game() does exactly what the name suggests. It sets up a new game of hangman. This means that it picks a random word from the supplied wordlist array and...
My assignment: Triplet Template Class Directions: Define a template class for a generic triplet. The private...
My assignment: Triplet Template Class Directions: Define a template class for a generic triplet. The private data member for the triplet is a generic array with three elements. The triplet ADT has the following functions:  default constructor  explicit constructor: initialize the data member using parameters  three accessors (three get functions) which will return the value of each individual element of the array data member  one mutator (set function) which will assign values to the data member...
**[70 pts]** You will be writing a (rather primitive) online store simulator. It will have these...
**[70 pts]** You will be writing a (rather primitive) online store simulator. It will have these classes: Product, Customer, and Store. All data members of each class should be marked as **private** (a leading underscore in the name). Since they're private, if you need to access them from outside the class, you should do so via get or set methods. Any get or set methods should be named per the usual convention ("get_" or "set_" followed by the name of...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT