Write a recursive Python function recursive_sum that takes a list of integers and returns the sum of all the numbers in the list.
Example Input: [1, 2, 3, 4, 5]
Example Output: 15
Solution
def recursive_sum(numbers):ifnot numbers: # if the list of numbers is emptyreturn0# return zeroelse: # otherwise# return sum the first num in the list and # the sum of the remaining items in the listreturn numbers[0] + recursive_sum(numbers[1:])recursive_sum([1, 2, 3, 4, 5])
15
Problem 6: Unique words
Write a Python function count_unique_words that takes a list of strings and returns the number of unique words in the list.
Example Input: ['apple', 'banana', 'apple', 'cherry', 'banana', 'date']
Example Output: 4
Solution
def count_unique_words(words): unique_words = [] # create an empty list to store the unique wordsfor word in words: # for each word in the original list of wordsif word notin unique_words: # if the word is not the unique list unique_words.append(word) # add that word to the unique listreturnlen(unique_words) # return the length of the list of the unique wordscount_unique_words(['apple', 'banana', 'apple', 'cherry', 'banana', 'date'])
4
Solution #2
def count_unique_words_v2(words):returnlen(set(words)) # return the length of the set version of the list wordscount_unique_words_v2(['apple', 'banana', 'apple', 'cherry', 'banana', 'date'])
4
Solution #3
def count_unique_words_v3(words):returnlen({word for word in words}) # Using list comprehensioncount_unique_words_v3(['apple', 'banana', 'apple', 'cherry', 'banana', 'date'])
4
Problem 7: Higher-Order Functions
Write a function named apply_operation that takes a list of numbers, a function that performs an operation on a single number (e.g., square, cube), and applies that operation to each number in the list, returning a new list.
Example Input: apply_operation([1, 2, 3, 4], lambda x: x**2)
Example Output: [1, 4, 9, 16]
Solution
def apply_operation(numbers, operation):return [operation(number) for number in numbers]apply_operation([1, 2, 3, 4], lambda x: x**2)
[1, 4, 9, 16]
Problem 8: Flatten a Nested List
Write a recursive Python function flatten that takes a nested list (a list containing other lists) and returns a flat list containing all the elements in the nested list, in the same order.
Example Input: flatten([1, [2, 3], [4, [5, 6]], 7])
Given a list of unique integers sorted in increasing order, write a Python function named find_missing that returns a list of any missing integers in the sequence from the minimum to the maximum value.