Question

In: Computer Science

THIS IS ALL ON PYTHON Recursion Practice Recall from lecture that a recursive function is one...

THIS IS ALL ON PYTHON

Recursion Practice

Recall from lecture that a recursive function is one that calls on itself. Recursive functions have two parts, the base case which stops the recursion and the recursive step where the function calls upon itself.

When designing recursive algorithms, your goal for each step should be to work towards the base case. More abstractly, each recursive call decreases the size of the problem, working ever closer to some trivial case with a defined solution.

uppercount(s)

Write a recursive function uppercount(s) that counts a number of uppercase letters in the input string. Do not use loops or built-in Python string functions (the only string functions you can use are slicing and indexing).

>>>> n = uppercount("Hello, World")
print(n)
2

Add comments to your code to point out the base case and the recursive case.

clean_string(s)

From the standpoint of Python, words like ”world” and ”world!” as different words. So if we wrote an automatic English-to-Spanish translator that replaced ”world” with ”mundo”, ”world” would have been replaced and ”world!” wouln’t. I.e. we notice that before we can write a program for automatic translation, we need to find a way to ignore punctuation in a string. Write a recursive function clean_string(s) that would remove all symbols that are not uppercase or lowercase letters or space from s and return the ”clean” string.

Do not use loops.

>>>> CS = clean_string("Hello, world") print(CS)
Hello world

Add comments to your code to point out the base case and the recursive case.

clean_list(lst1, lst2)

Using a similar idea to the one you employed in clean string(s) function, write a recursive function clean_list(l1, l2) that takes two lists as input and returns a list of elements from lst1 that are not present in lst2.

Do not use loops.

>>>> unique = clean_list([1,2,3,4,5,6,7], [2,4,6]) print(unique)
[1,3,5,7]

Add comments to your code to point out the base case and the recursive case.

Recursions vs. Iteration

As we discussed, recursion is a very powerful problem-solving technique. In fact, any computation can be expressed recursively. However, recursion doesn’t always lead to efficient solution, as you will now see. A classic example of recursion is the definition of Fibonacci number.

Wikipedia has a good article about it: Fibonacci Number. (Remember to check the part that talks about Fibonacci numbers in nature).

A Fibonacci number is defined as follows:

F(0) = 0
F(1) = 1
F(n) = F(n−1) + F(n−2) for n > 1.

Recursive Fibonacci

Write a recursive function F(n) that returns n-th Fibonacci number. In comments, mark the base case and recursive step.

Iterative Fibonacci

Write an iterative function (using iteration, i.e. loop(s)) f(n) that returns n-th Fibonacci number.

Solutions

Expert Solution

'''
Python version : 3.6
Python program to define recursive functions
'''

def uppercount(s):
   """
   Recurisve function that counts a number of uppercase letters in the input string.
   """
   # recursive step: number of characters in s > 0
   if len(s) > 0:
  
       # first character is uppercase, return 1 + number of uppercase characters in substring from index 1 to end
       if(s[0] >= 'A' and s[0] <= 'Z'):
           return 1 + uppercount(s[1:])
       else: # first character is not uppercase, return number of uppercase characters in substring from index 1 to end
           return uppercount(s[1:])
  
   else: # base step: empty string
       return 0
      
def clean_string(s):
   """
   Recurisve function that would remove all symbols that are not uppercase or lowercase
   letters or space from s and return the 'clean' string.
   """
   # recursive step: number of characters in s > 0
   if len(s) > 0:
       # first character is letter or space, return the first character + string obtained
       # by calling clean_string with substring from index 1 to end
       if((s[0] >= 'a' and s[0] <= 'z') or (s[0] >= 'A' and s[0] <= 'Z') or s[0] == ' '):
           return s[0] + clean_string(s[1:])
       else:
           # first character is not a letter or space, return the string obtained
           # by calling clean_string with substring from index 1 to end
           return clean_string(s[1:])
  
   else: # base step: empty string
       return ""

def clean_list(lst1, lst2):
   """
   Recurisve function that takes two lists as input and
   returns a list of elements from lst1 that are not present in lst2.
   """
   # recursive step: number of elements in lst1 > 0
   if len(lst1) > 0:
       # if first element of lst1 is not in lst2, return list containing first element of lst1 and
       # list returned by calling clean_list with sublist from index 1 to end and lst2
       if lst1[0] not in lst2:
           return lst1[0:1] + clean_list(lst1[1:], lst2)
       else:
           # if first element of lst1 is in lst2, return list returned by
           # calling clean_list with sublist from index 1 to end and lst2
           return clean_list(lst1[1:],lst2)
  
   else: # base step: empty list1
       return []
      
def fibonacci(n):
   """
   Recurisve function that returns n-th Fibonacci number
   """
   # base step: n <= 1 i.e n is 0 or 1, return n
   if n <= 1:
       return n
   else: # recursive step: n > 1 return sum of n-1 and n-2 fibonacci numbers
       return fibonacci(n-1) + fibonacci(n-2)
              
def f(n):
   """
   Iterative function that returns nth fibonacci number
   """
   # n<=1, return n
   if n <= 1:
       return n
   else: # n > 1
       # set f1 to 0 and f2 to 1 i.e first 2 fibonacci numbers
       f1 = 0
       f2 = 1
       c = 2 # set counter c to 2 (number of fibonacci numbers generated)
      
       # loop that continues until nth fibonacci number has been generated
       while c <= n:
           f3 = f1 + f2 # set f3 to f1+f2
           f1 = f2 # set f1 to f2
           f2 = f3 # set f2 ti f3
           c += 1 # increment c by 1
          
       # after loop nth fibonacci is in f2 and f3  
       return f3  
              
# test the functions              
print("uppercount(\"Hello, World\"):", uppercount("Hello, World"))      
print("clean_string(\"Hello, World\"):", clean_string("Hello, World"))
print("clean_list([1,2,3,4,5,6,7], [2,4,6]):",clean_list([1,2,3,4,5,6,7], [2,4,6]))
print("fibonacci(8):", fibonacci(8))
print("f(8):",f(8))

#end of program

Code Screenshot:

Output:


Related Solutions

1. Implement the recursive factorial function given below (from the lecture notes on recursion). Develop a...
1. Implement the recursive factorial function given below (from the lecture notes on recursion). Develop a main program that allows the user to enter any integer (positive) integer value, and displays the factorial of that value. The program should allow the user to either keep entering another value, or quit the program. public static int factorial(int n) { if (n == 0 || n == 1) return (1); else return (n * factorial(n-1)); } 2. Determine the largest value for...
C++ Recursion, Change the delete_node function in the header file to a recursive delete_node function, main...
C++ Recursion, Change the delete_node function in the header file to a recursive delete_node function, main is already set. Hint: It might be helpful to modify the function so that it uses a separate recursive function to perform whatever processing is needed. //////////////////////////////////////////////////////////////header.h////////////////////////////////////////////////////////////////////////////////////////////// #ifndef HEADER_H_ #define HEADER_H_ #include <iostream> using namespace std; template <class T> class LL { private:    struct LLnode    {        LLnode* fwdPtr;        T theData;    };    LLnode* head; public:    LL();...
Recursion java: 1. Write a recursive algorithm to add all the elements of an array of...
Recursion java: 1. Write a recursive algorithm to add all the elements of an array of n elements 2. Write a recursive algorithm to get the minimum element of an array of n elements 3. Write a recursive algorithm to add the corresponding elements of two arrays (A and B) of n elements. Store the results in a third array C .4. Write a recursive algorithm to get the maximum element of a binary tree 5. Write a recursive algorithm...
To get some practice with recursion. You can do all this in one driver program. Write...
To get some practice with recursion. You can do all this in one driver program. Write a recursive method to compute the result of the Fibonacci sequence: Fibonacci(N) = Fibonacci(N -1) + Fibonacci(N-2) N == 0 is 0 N == 1 is 1 Testing: Display the result for Fibonacci(N) and the number of function calls for N = 2, 5 and 10.
Recursion is a programming technique in which a function calls itself. This project applies recursion to a new problem, and illustrates the recursive implementation of backtracking.
RECURSIVELY FINDING PATHS THROUGH A MAZE in C++INTRODUCTIONRecursion is a programming technique in which a function calls itself. This project applies recursion to a new problem, and illustrates the recursive implementation of backtracking.DESCRIPTIONConsider finding all paths from an entrance on the top of a maze to an exit on the bottom. This task can be accomplished recursively, so in this project, you design, implement, test, and document a program that calls a recursive function to find a path through a maze.An...
One of your chapters this week is on recursion. Below are the three recursive algorithms laws:...
One of your chapters this week is on recursion. Below are the three recursive algorithms laws: 1. A recursive algorithm must have a base case. 2. A recursive algorithm must change its state and move toward the base case. 3. A recursive algorithm must call itself, recursively. Do you have any examples of recursive algorithms used in the real-world? Approximately 175 words in the answer.
Recursion. Question 1 1.1 What are the 2 main components of a recursive function? 1.2 What...
Recursion. Question 1 1.1 What are the 2 main components of a recursive function? 1.2 What is more efficient: an explicit loop structure or a recursive function? Explain your answer. 1.3 In what scenarios should a recursive solution be preferred to an iterative solution?
Learning objectives; File I/O practice, exceptions, binary search, recursion. Design and implement a recursive version of...
Learning objectives; File I/O practice, exceptions, binary search, recursion. Design and implement a recursive version of a binary search. Instead of using a loop to repeatedly check for the target value, use calls to a recursive method to check one value at a time. If the value is not the target, refine the search space and call the method again. The name to search for is entered by the user, as is the indexes that define the range of viable...
In python I want to create a function that takes in a linked list. Using recursion...
In python I want to create a function that takes in a linked list. Using recursion only, I want to check if the linked list is sorted. How do i do this?
1.)recursive merge sort on a list.(Python) 2.)recursive bubble sort using a list without enumerate() function.(python) Show...
1.)recursive merge sort on a list.(Python) 2.)recursive bubble sort using a list without enumerate() function.(python) Show Base case, and recursive case.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT