10.31. Exercises¶
-
Draw a reference diagram for
a
andb
before and after the third line of the following python code is executed:a = [1, 2, 3] b = a[:] b[0] = 5
Your diagram should show two variables referring to two different lists.
a
refers to the original list with 1,2, and 3.b
refers to a list with 5,2, and 3 since the zero-eth element was replaced with 5.
-
Create a list called
myList
with the following six items: 76, 92.3, “hello”, True, 4, 76. Begin with the empty list shown below, and add 6 statements to add each item, one per item. The first three statements should use the append method to append the item to the list, and the last three statements should use concatenation.
-
Starting with the list of the previous exercise, write Python statements to do the following:
Append “apple” and 76 to the list.
Insert the value “cat” at position 3.
Insert the value 99 at the start of the list.
Find the index of “hello”.
Count the number of 76s in the list.
Remove the first occurrence of 76 from the list.
Remove True from the list using
pop
andindex
.
-
Write a function called
average
that takes a list of numbers as a parameter and returns the average of the numbers.
-
Write a Python function named
max
that takes a parameter containing a nonempty list of integers and returns the maximum value. (Note: there is a builtin function namedmax
but pretend you cannot use it.)
-
Write a function
sum_of_squares(xs)
that computes the sum of the squares of the numbers in the listxs
. For example,sum_of_squares([2, 3, 4])
should return 4+9+16 which is 29:
-
Sum up all the even numbers in a list.
-
Count how many words in a list have length 5.
-
Count how many words occur in a list up to and including the first occurrence of the word “sam”.
-
Although Python provides us with many list methods, it is good practice and very instructive to think about how they are implemented. Implement a Python function that works like the following:
count
in
reverse
index
insert
-
Write a function
replace(s, old, new)
that replaces all occurences ofold
withnew
in a strings
:test(replace('Mississippi', 'i', 'I'), 'MIssIssIppI') s = 'I love spom! Spom is my favorite food. Spom, spom, spom, yum!' test(replace(s, 'om', 'am'), 'I love spam! Spam is my favorite food. Spam, spam, spam, yum!') test(replace(s, 'o', 'a'), 'I lave spam! Spam is my favarite faad. Spam, spam, spam, yum!')
Hint: use the
split
andjoin
methods.
-
Here are the rules for an L-system that creates something that resembles a common garden herb. Implement the following rules and try it. Use an angle of 25.7 degrees.
H H --> HFX[+H][-H] X --> X[-FFF][+FFF]FX
-
Here is another L-System. Use an Angle of 25.
F F --> F[-F]F[+F]F
-
Create a list named
randlist
containing 100 random integers between 0 and 1000 (use iteration, append, and the random module).