CS21: Quiz 3 Study Guide

In addition to all concepts from Quiz 1 and Quiz 2...

You should understand and/or be able to use the following Python concepts:

Practice problems:

  1. Write a program which asks the user for 4 words and then prints them in reverse order.

  2. Write a function called avgList that, given a list of numbers, calculates and returns their average. For example, avgList([5, 10, 5, 4]) should return 6. Write a main program to test the function.

  3. Write a function called maxList that, given a list of numbers, finds and returns the largest number in the list (without using the built-in max(..) function). For example, maxList([7,4,8,1]) should return 8. Write a main program to test the function.

  4. Consider the following program.

def main():
    print("in main")
    test = "whee"
    check = "e"
    answer = helper(test, check)
    print("the answer is %d" % (answer))

def helper(word, letter):
    print("in helper")
    print("word: %s" % (word))
    print("letter: %s" % (letter))
    x = 0
    for i in range(len(word)):
        if word[i] == letter:
            x = x+1

    # draw stack here, just before return
    return x

  1. Write a program that reads in student grades from the user, until the user enters a -1. After reading in the -1, the program should compute and display the average grade.
    Please enter your grades below.
    Enter a -1 when you are all done...

    grade  1: 98
    grade  2: 87
    grade  3: 65
    grade  4: 95
    grade  5: 80
    grade  6: -1

    The average of those 5 grades is 85.000
  1. Write a function called results(np, nc) that takes two parameters, the number of problems, and the number correct. The function should print an appropriate message to the user, based on the percentage the user got correct. For example, if they got 100% correct, print "Super!"; if they got 80% correct, print "Good job."; and so on. Here's a few examples:
  1. Analyze the following code:
m = ["t","i","m","e"]
s = "time"
m[1] = "a"
s[1] = "a"

What happens when this code is executed? What are the values of m and s afterward?

  1. Consider the following program.
def double(lst):
    total = 0
    for i in range(len(lst)):
      lst[i] = lst[i] * 2
      total += lst[i]

    # Q1: What is the function stack here?
    return total

def main():
    values = [-3, 4, 8, -5]
    test = double(values)
    print("Sum of doubles:", test)
    # Q2: What is the function stack here?

  1. Consider the following program.
def swap(i, j, lst):
    temp = lst[i]
    lst[i] = lst[j]
    # Q1: What is the stack here?
    lst[j] = temp

def mystery(lst):
    firstIdx = 0
    lastIdx = len(lst)-1
    while firstIdx < lastIdx:
        swap(lastIdx, firstIdx, lst)
        lastIdx = lastIdx - 1
        firstIdx = firstIdx + 1

def main():
    wordList = ["whose", "woods", "these", "are"]
    print("before:", wordList)
    print("after:", wordList)