Practice recursion on lists Practice multiple base conditions Combine recursion call with and,or not operators Search for an element in a list using recursion Instructions In this lab, we will write a recursive function for searching a list of integers/strings. Write a recursive function to determine if a list contains an element. Name the function recursive_search(aList, value), where aList is a list and value if primitive type is the object we want to search for. Return a boolean, specifically True if and only if value is an element of aList else return False from the function Examples: recursive_search([1,2,3], 2) == True recursive_search([1,2,3], 4) == False recursive_search([ ], 4) == False recursive_search([ [ 1 ], 2 ], 1) == False # -----> (because the list contains [ 1 ] and 2, not 1) Hint: Think about what the base case is? When is it obvious that the element is not in the list? If we are not at the base case, how can you use the information about the first element of the list to possibly see if the "value" exists in the list? Call the function recursively on a list of the last n-1 elements, essentially asking "does the element exist somewhere down the list"? Use that information when returning a value (True/False). For on a list of size n, make the recursive call on the last n-1 elements, also called the tail of the list.
- Practice recursion on lists
- Practice multiple base conditions
- Combine recursion call with and,or not operators
- Search for an element in a list using recursion
Instructions
In this lab, we will write a recursive function for searching a list of integers/strings.
Write a recursive function to determine if a list contains an element.
Name the function recursive_search(aList, value), where aList is a list and value if primitive type is the object we want to search for.
Return a boolean, specifically True if and only if value is an element of aList else return False from the function
Examples:
recursive_search([1,2,3], 2) == True recursive_search([1,2,3], 4) == False recursive_search([ ], 4) == False recursive_search([ [ 1 ], 2 ], 1) == False # -----> (because the list contains [ 1 ] and 2, not 1)
Hint:
Think about what the base case is? When is it obvious that the element is not in the list? If we are not at the base case, how can you use the information about the first element of the list to possibly see if the "value" exists in the list?
Call the function recursively on a list of the last n-1 elements, essentially asking "does the element exist somewhere down the list"? Use that information when returning a value (True/False).
For on a list of size n, make the recursive call on the last n-1 elements, also called the tail of the list.
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 1 images