224k views
3 votes
Implement a function that meets the specifications below.

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 """
# Your code here
For example,

max_val((5, (1,2), [[1],[2]])) returns 5.
max_val((5, (1,2), [[1],[9]])) returns 9.
Paste your entire function, including the definition, in the box below. Do not leave any debugging print statements.

2 Answers

2 votes

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.

User Charit
by
6.2k points
5 votes
def sum_digits(s):  result=0;  isSummed=False;  for char in s:    if char=="0" or char=="1" or char=="2" or char=="3" or char=="4" or char=="5" or char=="6" or char=="7" or char=="8" or char=="9":      result+=int(char);      if not isSummed:        isSummed=True;  if not isSummed:    raise ValueError();  else:    return int(result);
User Phtrivier
by
6.8k points