How to retrieve first name "Ana"
?
How to retrieve first name "Peter"
?
How to retrieve integer 23
?
How to retrieve first name "Ana"
?
How to retrieve first name "Peter"
?
How to retrieve integer 23
?
for
loopsIt returns the highest value among all the numbers in the list.
Test cases
def nested_max(lists):
max = None
for i in range(len(lists)):
for j in range(len(lists[i])):
if max == None or lists[i][j] > max:
max = lists[i][j]
return max
def main():
assert nested_max([[], []]) == None
assert nested_max([[1, 2, 3, 2, 1],
[2, 3, 2, 1, 5],
[0, 1]]) == 5
print("Passed all tests")
main()
Passed all tests
Draw a loop table with:
i
, j
,len(lists[i])
, lists[i][j]
, and max
for each nested loop iterationj
and lists[i][j]
are "-"
if an inner list is emptyi | j | len(lists[i]) | lists[i][j] | max |
---|---|---|---|---|
0 | - | 0 | - | None |
1 | - | 0 | - | None |
2 | 0 | 2 | 2 | 2 |
2 | 1 | 2 | 1 | 2 |
3 | 0 | 2 | 0 | 2 |
3 | 1 | 2 | 5 | 5 |
def max_list(numbers):
max = None
for n in numbers:
if max == None or n > max:
max = n
return max
def nested_max(lists):
max = None
for i in range(len(lists)):
max_of_sublist = max_list(lists[i])
if max == None or max_of_sublist > max:
max = max_of_sublist
return max
def main():
assert nested_max([[1, 2, 3, 2, 1],
[],
[5, 1]]) == 5
main()
It returns the lowest number in all inner lists.
Test cases:
def nested_min(lists):
min = None
for i in range(len(lists)):
for j in range(len(lists[i])):
if min == None or lists[i][j] < min:
min = lists[i][j]
return min
def main():
assert nested_min([[], []]) == None
assert nested_min([[1, 2, 3, 2, 1],
[2, 3, 2, 1, 5],
[0, 1]]) == 0
print("Passed all tests")
main()
Passed all tests
You have 10 minutes to complete the quiz.
In addition to retrieving a value from nested lists, we can also mutate a value in a sublist.
It mutates the sublist items by multiplying each number in each sublist by 2 and returns the argument list.
Test cases
It mutates the sublist items by reversing each string (use string[::-1]
to reverse it) and returns the argument list.
Name file reverse_strings.py
and submit your attendance.
Test cases:
def reverse_strings_nested(strings):
for i in range(len(strings)):
for j in range(len(strings[i])):
strings[i][j] = strings[i][j][::-1]
return strings
def main():
original_strings = [["desserts", "raw", "live"],
["smart", "knits"]]
reverse_strings_nested(original_strings)
assert original_strings == [["stressed", "war", "evil"],
["trams", "stink"]]
print(original_strings)
main()
[['stressed', 'war', 'evil'], ['trams', 'stink']]