Skip to main content

Exercises 10.31 Exercises

1.

Solution.
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.

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.

2.

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.

Solution.
myList = []
myList.append(76)
myList.append(92.3)
myList.append("hello")
myList = myList + [True]
myList = myList + [4]
myList = myList + [76]
print(myList)

3.

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.

Solution.
myList = [76, 92.3, 'hello', True, 4, 76]

myList.append("apple")         # a
myList.append(76)              # a
myList.insert(3, "cat")        # b
myList.insert(0, 99)           # c

print(myList.index("hello"))   # d
print(myList.count(76))        # e
myList.remove(76)              # f
myList.pop(myList.index(True)) # g

print (myList)

4.

Write a function called average that takes a list of numbers as a parameter and returns the average of the numbers.

Solution.
def average(numlist):

    total = 0
    for num in numlist:
        total = total + num

    return total / len(numlist)

5.

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 named max but pretend you cannot use it.)

Solution.
def max(lst):
    max = 0
    for e in lst:
        if e > max:
            max = e
    return max

6.

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:

7.

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

Solution.
import random

def countOdd(lst):
    odd = 0
    for e in lst:
        if e % 2 != 0:
            odd = odd + 1
    return odd

# make a random list to test the function
lst = []
for i in range(100):
    lst.append(random.randint(0, 1000))

print(countOdd(lst))

8.

Sum up all the even numbers in a list.

9.

Sum up all the negative numbers in a list.

Solution.
import random

def sumNegative(lst):
    sum = 0
    for e in lst:
        if e < 0:
            sum = sum + e
    return sum

lst = []
for i in range(100):
    lst.append(random.randrange(-1000, 1000))

print(sumNegative(lst))

10.

Count how many words in a list have length 5.

11.

Solution.
import random

def sum(lst):
    sum = 0
    index = 0
    while index < len(lst) and lst[index] % 2 != 0:
        sum = sum + lst[index]
        index = index + 1
    return sum

lst = []
for i in range(100):
    lst.append(random.randint(0,1000))

print(sum(lst))

12.

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

13.

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

Solution.
def count(obj, lst):
    count = 0
    for e in lst:
        if e == obj:
            count = count + 1
    return count

def is_in(obj, lst):  # cannot be called in() because in is a reserved keyword
    for e in lst:
        if e == obj:
            return True
    return False

def reverse(lst):
    reversed = []
    for i in range(len(lst)-1, -1, -1): # step through the original list backwards
        reversed.append(lst[i])
    return reversed

def index(obj, lst):
    for i in range(len(lst)):
        if lst[i] == obj:
            return i
    return -1

def insert(obj, index, lst):
    newlst = []
    for i in range(len(lst)):
        if i == index:
            newlst.append(obj)
        newlst.append(lst[i])
    return newlst

lst = [0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9]
print(count(1, lst))
print(is_in(4, lst))
print(reverse(lst))
print(index(2, lst))
print(insert('cat', 4, lst))

14.

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.

15.

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
Solution.
import turtle

def createLSystem(numIters, axiom):
    startString = axiom
    endString = ""
    for i in range(numIters):
        endString = processString(startString)
        startString = endString

    return endString

def processString(oldStr):
    newstr = ""
    for ch in oldStr:
        newstr = newstr + applyRules(ch)

    return newstr

def applyRules(ch):
    newstr = ""
    if ch == 'H':
        newstr = 'HFX[+H][-H]'   # Rule 1
    elif ch == 'X':
        newstr = 'X[-FFF][+FFF]FX'
    else:
        newstr = ch     # no rules apply so keep the character

    return newstr

def drawLsystem(aTurtle, instructions, angle, distance):
    savedInfoList = []
    for cmd in instructions:
        if cmd == 'F':
            aTurtle.forward(distance)
        elif cmd == 'B':
            aTurtle.backward(distance)
        elif cmd == '+':
            aTurtle.right(angle)
        elif cmd == '-':
            aTurtle.left(angle)
        elif cmd == '[':
            savedInfoList.append([aTurtle.heading(), aTurtle.xcor(), aTurtle.ycor()])
            #print(savedInfoList)
        elif cmd == ']':
            newInfo = savedInfoList.pop()
            aTurtle.setheading(newInfo[0])
            aTurtle.setposition(newInfo[1], newInfo[2])


def main():
    inst = createLSystem(4, "H")   # create the string
    print(inst)
    t = turtle.Turtle()            # create the turtle
    wn = turtle.Screen()
    t.up()
    t.back(200)
    t.down()
    t.speed(9)
    drawLsystem(t, inst, 27.5, 5)  # draw the picture

    wn.exitonclick()

main()

16.

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

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

17.

Create a list named randlist containing 100 random integers between 0 and 1000 (use iteration, append, and the random module).

Solution.
import random

randlist = []
for i in range(100):
    randlist.append(random.randint(0, 1000))
You have attempted of activities on this page.