Week 6
Week 6
Lecture 1:
rangeis typically used in a for loop to iterate over a sequence of numbers. Here are
some examples:
# Iterate over the numbers 0, 1, 2, 3, and 4.
for i in range(5):
Because len returns the number of items in a list, it can be used with range to
iterate over all the indices. This loop prints all the values in a list:
for i in range(len(lst)):
print(lst[i])
This also gives us flexibility to process only part of a list. For example, We can
print only the first half of the list:
for i in range(len(lst) // 2):
print(lst[i])
Example 1
>>> count_adjacent_repeats('abccdeffggh')
3
'''
repeats = 0
return repeats
We want to compare a character in the string with another character in the string
beside it. This is why we iterate over the indices because the location is important,
and only knowing the value of the character does not provide us with enough
information. This is how we are able to count repeated characters in a string. We
can't execute the body of the loop if i is len(s) - 1 because we compare to s[i +
1], and that would produce an IndexError.
Example 2
Shift each item in L one position to the left and shift the first item
to
the last position.
first_item = L[0]
L[-1] = first_item
For the same reasons as above, merely knowing the value of the items in the list is
not enough since we need to know where the items are located; we need to know
the index (position) of the item in the list.
LECTURE 2:
Nested Loops
Bodies of Loops
The bodies of loops can contain any statements, including other loops. When this
occurs, this is known as a nested loop.
Notice that when i is 10, the inner loop executes in its entirety, and only after j has
ranged from 1 through 4 is i assigned the value 11.
Return a new list in which each item is the average of the grades in
the
inner list at the corresponding position of grades.
>>> calculate_averages([[70, 75, 80], [70, 80, 90, 100], [80, 100]])
[75.0, 85.0, 90.0]
'''
averages = []
averages.append(total / len(grades_list))
return averages
In calculate_averages, the outer for loop iterates through each sublist in grades.
We then calculate the average of that sublist using a nested, or inner, loop, and add
the average to the accumulator (the new list, averages).
LECTURE 3: