10.10. Exercises

  1. Draw a reference diagram for a and b 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.

    Show Comments
  1. 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)

  1. Starting with the list of the previous exercise, write Python statements to do the following:

    1. Append “apple” and 76 to the list.

    2. Insert the value “cat” at position 3.

    3. Insert the value 99 at the start of the list.

    4. Find the index of “hello”.

    5. Count the number of 76s in the list.

    6. Remove the first occurrence of 76 from the list.

    7. Remove True from the list using pop and index.

    (ex_9_3)

    14
     
    1
    myList = [76, 92.3, 'hello', True, 4, 76]
    2
    3
    myList.append("apple")         # a
    4
    myList.append(76)              # a
    5
    myList.insert(3, "cat")        # b
    6
    myList.insert(0, 99)           # c
    7
    8
    print(myList.index("hello"))   # d
    9
    print(myList.count(76))        # e
    10
    myList.remove(76)              # f
    11
    myList.pop(myList.index(True)) # g
    12
    13
    print (myList)
    14

    (ex_9_3_answer)

    Show Comments
  1. 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)

  1. 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)

    15
     
    1
    import random
    2
    3
    def max(lst):
    4
        max = 0
    5
        for e in lst:
    6
            if e > max:
    7
                max = e
    8
        return max
    9
    10
    lst = []
    11
    for i in range(100):
    12
        lst.append(random.randint(0, 1000))
    13
    14
    print(max(lst))
    15

    (lst_q5_answer)

    Show Comments
  1. Write a function sum_of_squares(xs) that computes the sum of the squares of the numbers in the list xs. For example, sum_of_squares([2, 3, 4]) should return 4+9+16 which is 29:

    (ex_7_11)

  1. Write a function to count how many odd numbers are in a list.

    (ex_9_6)

    16
     
    1
    import random
    2
    3
    def countOdd(lst):
    4
        odd = 0
    5
        for e in lst:
    6
            if e % 2 != 0:
    7
                odd = odd + 1
    8
        return odd
    9
    10
    # make a random list to test the function
    11
    lst = []
    12
    for i in range(100):
    13
        lst.append(random.randint(0, 1000))
    14
    15
    print(countOdd(lst))
    16

    (lst_q7_answer)

    Show Comments
  1. Sum up all the even numbers in a list.

    (ex_9_7)

  1. Sum up all the negative numbers in a list.

    (ex_9_8)

    15
     
    1
    import random
    2
    3
    def sumNegative(lst):
    4
        sum = 0
    5
        for e in lst:
    6
            if e < 0:
    7
                sum = sum + e
    8
        return sum
    9
    10
    lst = []
    11
    for i in range(100):
    12
        lst.append(random.randrange(-1000, 1000))
    13
    14
    print(sumNegative(lst))
    15

    (lst_q9_answer)

    Show Comments
  1. Count how many words in a list have length 5.

    (ex_9_9)

  1. Sum all the elements in a list up to but not including the first even number.

    (ex_9_10)

    16
     
    1
    import random
    2
    3
    def sum(lst):
    4
        sum = 0
    5
        index = 0
    6
        while index < len(lst) and lst[index] % 2 != 0:
    7
            sum = sum + lst[index]
    8
            index = index + 1
    9
        return sum
    10
    11
    lst = []
    12
    for i in range(100):
    13
        lst.append(random.randint(0,1000))
    14
    15
    print(sum(lst))
    16

    (lst_q11_answer)

    Show Comments
  1. Count how many words occur in a list up to and including the first occurrence of the word “sam”.

    (ex_9_11)

  1. 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:

    1. count

    2. in

    3. reverse

    4. index

    5. insert

    (ex_9_12)

    40
     
    1
    def count(obj, lst):
    2
        count = 0
    3
        for e in lst:
    4
            if e == obj:
    5
                count = count + 1
    6
        return count
    7
    8
    def is_in(obj, lst):  # cannot be called in() because in is a reserved keyword
    9
        for e in lst:
    10
            if e == obj:
    11
                return True
    12
        return False
    13
    14
    def reverse(lst):
    15
        reversed = []
    16
        for i in range(len(lst)-1, -1, -1): # step through the original list backwards
    17
            reversed.append(lst[i])
    18
        return reversed
    19
    20
    def index(obj, lst):
    21
        for i in range(len(lst)):
    22
            if lst[i] == obj:
    23
                return i
    24
        return -1
    25
    26
    def insert(obj, index, lst):
    27
        newlst = []
    28
        for i in range(len(lst)):
    29
            if i == index:
    30
                newlst.append(obj)
    31
            newlst.append(lst[i])
    32
        return newlst
    33
    34
    lst = [0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9]
    35
    print(count(1, lst))
    36
    print(is_in(4, lst))
    37
    print(reverse(lst))
    38
    print(index(2, lst))
    39
    print(insert('cat', 4, lst))
    40

    (lst_q13_answer)

    Show Comments
  1. Write a function replace(s, old, new) that replaces all occurences of old with new in a string s:

    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 and join methods.

    (ex_9_13)

  1. 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)

    64
     
    1
    import turtle
    2
    3
    def createLSystem(numIters, axiom):
    4
        startString = axiom
    5
        endString = ""
    6
        for i in range(numIters):
    7
            endString = processString(startString)
    8
            startString = endString
    9
    10
        return endString
    11
    12
    def processString(oldStr):
    13
        newstr = ""
    14
        for ch in oldStr:
    15
            newstr = newstr + applyRules(ch)
    16
    17
        return newstr
    18
    19
    def applyRules(ch):
    20
        newstr = ""
    21
        if ch == 'H':
    22
            newstr = 'HFX[+H][-H]'   # Rule 1
    23
        elif ch == 'X':
    24
            newstr = 'X[-FFF][+FFF]FX'
    25
        else:
    26
            newstr = ch     # no rules apply so keep the character
    27
    28
        return newstr
    29
    30
    def drawLsystem(aTurtle, instructions, angle, distance):
    31
        savedInfoList = []
    32
        for cmd in instructions:
    33
            if cmd == 'F':
    34
                aTurtle.forward(distance)
    35
            elif cmd == 'B':
    36
                aTurtle.backward(distance)
    37
            elif cmd == '+':
    38
                aTurtle.right(angle)
    39
            elif cmd == '-':
    40
                aTurtle.left(angle)
    41
            elif cmd == '[':
    42
                savedInfoList.append([aTurtle.heading(), aTurtle.xcor(), aTurtle.ycor()])
    43
                #print(savedInfoList)
    44
            elif cmd == ']':
    45
                newInfo = savedInfoList.pop()
    46
                aTurtle.setheading(newInfo[0])
    47
                aTurtle.setposition(newInfo[1], newInfo[2])
    48
    49
    50
    def main():
    51
        inst = createLSystem(4, "H")   # create the string
    52
        print(inst)
    53
        t = turtle.Turtle()            # create the turtle
    54
        wn = turtle.Screen()
    55
        t.up()
    56
        t.back(200)
    57
        t.down()
    58
        t.speed(9)
    59
        drawLsystem(t, inst, 27.5, 5)  # draw the picture
    60
    61
        wn.exitonclick()
    62
    63
    main()
    64

    (lst_q15_answer)

    Show Comments
  1. Here is another L-System. Use an Angle of 25.

    F
    F --> F[-F]F[+F]F
    

    (ex_9_16)

Next Section - 11. Classes and Objects