10.10. 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. Do it with both append and with concatenation, one item at a time.(ex_9_2)
-
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
.
(ex_9_3)
141myList = [76, 92.3, 'hello', True, 4, 76]
2
3myList.append("apple") # a
4myList.append(76) # a
5myList.insert(3, "cat") # b
6myList.insert(0, 99) # c
7
8print(myList.index("hello")) # d
9print(myList.count(76)) # e
10myList.remove(76) # f
11myList.pop(myList.index(True)) # g
12
13print (myList)
14
(ex_9_3_answer)
-
Create a list containing 100 random integers between 0 and 1000 (use iteration, append, and the random module). Write a function called
average
that will take the list as a parameter and return the average.(ex_9_4)
-
Write a Python function that will take a the list of 100 random integers between 0 and 1000 and return the maximum value. (Note: there is a builtin function named
max
but pretend you cannot use it.)(ex_9_5)
151import random
2
3def max(lst):
4max = 0
5for e in lst:
6if e > max:
7max = e
8return max
9
10lst = []
11for i in range(100):
12lst.append(random.randint(0, 1000))
13
14print(max(lst))
15
(lst_q5_answer)
-
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:(ex_7_11)
-
Write a function to count how many odd numbers are in a list.
(ex_9_6)
161import random
2
3def countOdd(lst):
4odd = 0
5for e in lst:
6if e % 2 != 0:
7odd = odd + 1
8return odd
9
10# make a random list to test the function
11lst = []
12for i in range(100):
13lst.append(random.randint(0, 1000))
14
15print(countOdd(lst))
16
(lst_q7_answer)
-
Sum up all the even numbers in a list.
(ex_9_7)
-
Sum up all the negative numbers in a list.
(ex_9_8)
151import random
2
3def sumNegative(lst):
4sum = 0
5for e in lst:
6if e < 0:
7sum = sum + e
8return sum
9
10lst = []
11for i in range(100):
12lst.append(random.randrange(-1000, 1000))
13
14print(sumNegative(lst))
15
(lst_q9_answer)
-
Count how many words in a list have length 5.
(ex_9_9)
-
Sum all the elements in a list up to but not including the first even number.
(ex_9_10)
161import random
2
3def sum(lst):
4sum = 0
5index = 0
6while index < len(lst) and lst[index] % 2 != 0:
7sum = sum + lst[index]
8index = index + 1
9return sum
10
11lst = []
12for i in range(100):
13lst.append(random.randint(0,1000))
14
15print(sum(lst))
16
(lst_q11_answer)
-
Count how many words occur in a list up to and including the first occurrence of the word “sam”.
(ex_9_11)
-
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
(ex_9_12)
401def count(obj, lst):
2count = 0
3for e in lst:
4if e == obj:
5count = count + 1
6return count
7
8def is_in(obj, lst): # cannot be called in() because in is a reserved keyword
9for e in lst:
10if e == obj:
11return True
12return False
13
14def reverse(lst):
15reversed = []
16for i in range(len(lst)-1, -1, -1): # step through the original list backwards
17reversed.append(lst[i])
18return reversed
19
20def index(obj, lst):
21for i in range(len(lst)):
22if lst[i] == obj:
23return i
24return -1
25
26def insert(obj, index, lst):
27newlst = []
28for i in range(len(lst)):
29if i == index:
30newlst.append(obj)
31newlst.append(lst[i])
32return newlst
33
34lst = [0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9]
35print(count(1, lst))
36print(is_in(4, lst))
37print(reverse(lst))
38print(index(2, lst))
39print(insert('cat', 4, lst))
40
(lst_q13_answer)
-
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.(ex_9_13)
-
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
(ex_9_14)
641import turtle
2
3def createLSystem(numIters, axiom):
4startString = axiom
5endString = ""
6for i in range(numIters):
7endString = processString(startString)
8startString = endString
9
10return endString
11
12def processString(oldStr):
13newstr = ""
14for ch in oldStr:
15newstr = newstr + applyRules(ch)
16
17return newstr
18
19def applyRules(ch):
20newstr = ""
21if ch == 'H':
22newstr = 'HFX[+H][-H]' # Rule 1
23elif ch == 'X':
24newstr = 'X[-FFF][+FFF]FX'
25else:
26newstr = ch # no rules apply so keep the character
27
28return newstr
29
30def drawLsystem(aTurtle, instructions, angle, distance):
31savedInfoList = []
32for cmd in instructions:
33if cmd == 'F':
34aTurtle.forward(distance)
35elif cmd == 'B':
36aTurtle.backward(distance)
37elif cmd == '+':
38aTurtle.right(angle)
39elif cmd == '-':
40aTurtle.left(angle)
41elif cmd == '[':
42savedInfoList.append([aTurtle.heading(), aTurtle.xcor(), aTurtle.ycor()])
43#print(savedInfoList)
44elif cmd == ']':
45newInfo = savedInfoList.pop()
46aTurtle.setheading(newInfo[0])
47aTurtle.setposition(newInfo[1], newInfo[2])
48
49
50def main():
51inst = createLSystem(4, "H") # create the string
52print(inst)
53t = turtle.Turtle() # create the turtle
54wn = turtle.Screen()
55t.up()
56t.back(200)
57t.down()
58t.speed(9)
59drawLsystem(t, inst, 27.5, 5) # draw the picture
60
61wn.exitonclick()
62
63main()
64
(lst_q15_answer)
-
Here is another L-System. Use an Angle of 25.
F F --> F[-F]F[+F]F
(ex_9_16)