Final answer:
The 'max_val' function recursively finds the maximum integer in a tuple or list, which can contain nested lists or tuples. The function traverses all elements and sub-elements, updating the max_value when a larger integer is found.
Step-by-step explanation:
To solve the problem given by the student, we need to write a recursive function that traverses through the tuple or list and finds the maximum integer value, whether it is directly within the tuple/list or nested inside another tuple/list. Here is how we can implement the said function:
def max_val(t):
""" t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t """
max_value = None
for element in t:
if isinstance(element, (list, tuple)):
value = max_val(element)
else:
value = element
if max_value is None or value > max_value:
max_value = value
return max_value
The function starts with setting max_value to None, then it iterates through each element in the given tuple or list. If the element is a tuple or list itself, it calls max_val recursively to find the maximum value within that sublist/tuple. Otherwise, it treats the element as an integer and compares it to the current max_value. At the end of the function, the highest integer found is returned.