'l'
Review session tomorrow (Tuesday, Feb 18)
Location: Gittings 129b
Time: 5 - 7 : 00 pm
We’ve worked with strings
, which are sequences in Python. Sequences can be indexed with [ ]
:
We also have lists
in Python, which are also sequences and can indexed with [ ]
:
lists
are a data structure that is:
Its name is sum_all
that takes a list of values
as an argument. It runs a loop that iterates through the number in values
summing all numbers. It returns the sum of all numbers in values
. HINT: a) create a variable that accumulate the sum and b) use while
.
Name your file sum_list.py
and submit to Gradescope.
We start with index = 0
and total = 0
:
index | index < len(values) | values[index] | total |
---|---|---|---|
0 | True | 2 | 0 + 2 = 2 |
1 | True | 1 | 2 + 1 = 3 |
2 | True | 5 | 3 + 5 = 8 |
3 | True | 2 | 8 + 2 = 10 |
4 | True | 3 | 10 + 3 = 13 |
5 | False | - | 13 |
Start with index = 0
and total = 0
:
index | index < len(values) | values[index] | total |
---|---|---|---|
| | |||
| | |||
| | |||
| | |||
| | |||
| |
index | index < len(numbers) | numbers[index] | total |
---|---|---|---|
0 | True | 2 | 2 |
1 | True | 1 | 3 |
2 | True | 3 | 6 |
3 | True | 4 | 10 |
4 | False | - | 10 |
You can also visualize code in python on Python Tutor
Remember how to get the max of three numbers?
def max3(x, y, z):
max = x # assume max is first number
if y > max:
max = y # assumption is incorrect, assume y is max
if z > max:
max = z # assumption is incorrect, z is max
return max
def main():
print( max3(1, 2, 2) ) # 2
main()
2
Adapt this function (max_list
) to take a list of numbers (for example [1, 2, 2, 1, 3, 1, 1]
) instead of three numbers (use while
).
def max_list(numbers):
'''
Given a list of number, this function returns the highest number.
Args:
List of numeric values
Returns:
Max (float or integer, whatever value type is the highest)
'''
max = numbers[0]
index = 1
while index < len(numbers):
if numbers[index] > max:
max = numbers[index]
index += 1
return max
def main():
print( max_list([1, 2, 2, 1, 3, 1, 1]) ) # 3
print( max_list([3, 2, 2, 1, 0, 1, 1]) ) # 3
main()
3
3
We start with index = 1
and max = 2
:
index | index < len(numbers) | numbers[index] | max |
---|---|---|---|
| | |||
| | |||
| | |||
| | |||
| | |||
| |
We start with index = 1
and max = 2
:
index | index < len(numbers) | numbers[index] | max |
---|---|---|---|
1 | True | 1 | 2 |
2 | True | 3 | 3 |
3 | True | 1 | 3 |
4 | False | - | 3 |
Can we swap the two expressions at line 5
?
Its name is double
that takes a list of numeric variables as argument. It iterates over the list (use while
) doubling (multiplying by two) each value in the list. It returns the modified list.
list[2:4]
list[:]
list[:-1]
The same slicing can be done with strings