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
loopsnested_max
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
def max_list(numbers):
max = None
for i in range(len(numbers)):
if max == None or numbers[i] > max:
max = numbers[i]
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([[], []]) == 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
Submit your nested_max
functions to Gradescope for attendance.
Name your file nested_max.py
nested_min
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
In addition to retrieving a value from nested lists, we can also mutate a value in a sublist.
double_nested
Test cases
len_strings_nested
Test cases:
def len_strings_nested(strings):
for i in range(len(strings)):
for j in range(len(strings[i])):
strings[i][j] = len(strings[i][j])
return strings
def main():
original_list = [["desserts", "raw", "live"],
["smart", "knits"]]
assert len_strings_nested(original_list) == [[8, 3, 4], [5, 5]]
print(original_list)
main()
[[8, 3, 4], [5, 5]]
reverse_strings_nested
string[::-1]
to reverse it)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)
print("Passed test")
main()
[['stressed', 'war', 'evil'], ['trams', 'stink']]
Passed test
Draw a loop table with:
max
before loop, and in each iteration of the nested loopsi
, j
, and lists[i][j]
for each nested loop iterationi | 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 | 3 | 0 | 2 |
3 | 1 | 3 | 5 | 5 |
3 | 2 | 3 | 2 | 5 |
i | j | len(lists[i]) | lists[i][j] | max |
---|---|---|---|---|
4 | 0 | 1 | 3 | 5 |