'u'
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:
sum_all
numbers
as an argumentnumbers
summing all values (HINT: you need to create a variable that will aggregate or accumulate the sum)numbers
while
(define an index
before the loop, use index in the while
condition, change the index
inside the loop)Add test cases to the solution below:
Submit your sum_all
function to Gradescope for attendance.
Name your file sum_list.py
index | index < len(numbers) | numbers[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 |
index | index < len(numbers) | numbers[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
Activity: adapt this function (max_list
) to take a list of numbers instead of three numbers.
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
index | index < len(numbers) | numbers[index] | max |
---|---|---|---|
| | |||
| | |||
| | |||
| | |||
| | |||
| |
index | index < len(numbers) | numbers[index] | max |
---|---|---|---|
1 | True | 1 | 2 |
2 | True | 3 | 3 |
3 | True | 1 | 3 |
4 | False | - | 3 |
double
while
) doubling (multiplying by two) each value in the listName your file double.py
and submit it to gradescope.
list[2:4]
list[:]
list[:-1]
The same slicing can be done with strings