Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function to find max element in a list - Python Program

Example 1 :

def max_in_list(lst): """Find max element recursively.""" if len(lst) == 1: return lst[0] max_rest = max_in_list(lst[1:]) return lst[0] if lst[0] > max_rest else max_rest print(max_in_list([3, 9, 1, 7, 4]))

Output

 
OUTPUT  :
9 

Example 2 : Advanced Program

def find_max_recursive(data_list): """ Recursively finds the maximum element in a list. Args: data_list: The list of numbers to search. Returns: The maximum element in the list. """ if not data_list: raise ValueError("List cannot be empty") if len(data_list) == 1: return data_list[0] else: # Compare the first element with the maximum of the rest of the list max_of_rest = find_max_recursive(data_list[1:]) return data_list[0] if data_list[0] > max_of_rest else max_of_rest # Example Usage my_list1 = [1, 5, 2, 8, 3] max_element1 = find_max_recursive(my_list1) print(f"The maximum element in {my_list1} is: {max_element1}") my_list2 = [100, 20, 50, 10] max_element2 = find_max_recursive(my_list2) print(f"The maximum element in {my_list2} is: {max_element2}") my_list3 = [7] max_element3 = find_max_recursive(my_list3) print(f"The maximum element in {my_list3} is: {max_element3}") # Example with an empty list (will raise an error) try: find_max_recursive([]) except ValueError as e: print(f"Error: {e}")

Output

 
OUTPUT  :
The maximum element in [1, 5, 2, 8, 3] is: 8
The maximum element in [100, 20, 50, 10] is: 100
The maximum element in [7] is: 7
Error: List cannot be empty