10.10. Exercises¶
-
Draw a reference diagram for
aandbbefore 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.
arefers to the original list with 1,2, and 3.brefers to a list with 5,2, and 3 since the zero-eth element was replaced with 5.
-
Create a list called
myListwith 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
popandindex.
(ex_9_3)
141myList = [76, 92.3, 'hello', True, 4, 76]23myList.append("apple") # a4myList.append(76) # a5myList.insert(3, "cat") # b6myList.insert(0, 99) # c78print(myList.index("hello")) # d9print(myList.count(76)) # e10myList.remove(76) # f11myList.pop(myList.index(True)) # g1213print (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
averagethat 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
maxbut pretend you cannot use it.)(ex_9_5)
151import random23def max(lst):4max = 05for e in lst:6if e > max:7max = e8return max910lst = []11for i in range(100):12lst.append(random.randint(0, 1000))1314print(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 random23def countOdd(lst):4odd = 05for e in lst:6if e % 2 != 0:7odd = odd + 18return odd910# make a random list to test the function11lst = []12for i in range(100):13lst.append(random.randint(0, 1000))1415print(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 random23def sumNegative(lst):4sum = 05for e in lst:6if e < 0:7sum = sum + e8return sum910lst = []11for i in range(100):12lst.append(random.randrange(-1000, 1000))1314print(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 random23def sum(lst):4sum = 05index = 06while index < len(lst) and lst[index] % 2 != 0:7sum = sum + lst[index]8index = index + 19return sum1011lst = []12for i in range(100):13lst.append(random.randint(0,1000))1415print(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 = 03for e in lst:4if e == obj:5count = count + 16return count78def is_in(obj, lst): # cannot be called in() because in is a reserved keyword9for e in lst:10if e == obj:11return True12return False1314def reverse(lst):15reversed = []16for i in range(len(lst)-1, -1, -1): # step through the original list backwards17reversed.append(lst[i])18return reversed1920def index(obj, lst):21for i in range(len(lst)):22if lst[i] == obj:23return i24return -12526def insert(obj, index, lst):27newlst = []28for i in range(len(lst)):29if i == index:30newlst.append(obj)31newlst.append(lst[i])32return newlst3334lst = [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 ofoldwithnewin 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
splitandjoinmethods.(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 turtle23def createLSystem(numIters, axiom):4startString = axiom5endString = ""6for i in range(numIters):7endString = processString(startString)8startString = endString910return endString1112def processString(oldStr):13newstr = ""14for ch in oldStr:15newstr = newstr + applyRules(ch)1617return newstr1819def applyRules(ch):20newstr = ""21if ch == 'H':22newstr = 'HFX[+H][-H]' # Rule 123elif ch == 'X':24newstr = 'X[-FFF][+FFF]FX'25else:26newstr = ch # no rules apply so keep the character2728return newstr2930def 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])484950def main():51inst = createLSystem(4, "H") # create the string52print(inst)53t = turtle.Turtle() # create the turtle54wn = turtle.Screen()55t.up()56t.back(200)57t.down()58t.speed(9)59drawLsystem(t, inst, 27.5, 5) # draw the picture6061wn.exitonclick()6263main()64(lst_q15_answer)
-
Here is another L-System. Use an Angle of 25.
F F --> F[-F]F[+F]F
(ex_9_16)