Introduction to Computer Science

Quiz 4 Study Guide

This page contains a list of things you should know before taking Quiz 4. If you have any questions as to the correct answers to any of these questions, please let me know.

Functions

Our recent discussions have relied more upon functions as a means of defining useful pieces of a program. You should understand how functions are called, how arguments are assigned to parameters, and how values are returned. Here are some especially important details you should know:

Lists and Functions

We have also used lists in multiple labs and discussed how lists interact with functions. Consider, for instance, the following code:

def extend_list(lst, x):
  lst.append(x)
def main():
  data = [1,2]
  extend_list(data, 4)
  print data
main()

When this program is executed, it prints [1, 2, 4]. Even though the data variable is not changed within the main function, the data variable is a reference to a list (rather than the list itself). For more information, please see the textbook.

Exercises

Write the following Python functions:

Answer the following questions:

Stack Diagrams

We have discussed the syntax of stack diagrams and you have used them in the written portion of a lab. You should be familiar with how we draw stack diagrams. For a small presentation on how stack diagrams follow the execution of a program, please see this presentation (which also appears on the course schedule).

Exercises

For the following code, draw a stack diagram for the first time that the program reaches each comment.

def extend(lst1, lst2):
  for x in lst2:
    lst1.append(x)
  # Stack diagram!
def main():
  data1 = [1,2,3]
  data2 = [4,5]
  # Stack diagram!
  extend(data1,data2)
  print data1
  print data2
main()

Debugging and Execution Tracing

As always, you should be able to find mistakes in programs and understand how programs execute. You should be prepared to work out how a program will run without the use of a computer.

Exercises

Work out by hand what each of the following programs will print.

#1

def collatz(n):
  if n % 2 == 0:
    return n / 2
  else:
    return n*3 + 1
def main():
  i = 6
  while i > 1:
    print i
    i = collatz(i)
main()

#2

def num_or_zero(s):
  try:
    x = int(s)
    print x
    return x
  except ValueError:
    return 0
def sum_string(s):
  acc = 0
  for c in s:
    acc += num_or_zero(c)
  return acc
def main():
  print "#%s" % sum_string("10 hot dogs and 8 buns")
  print "$%s" % sum_string("4 and 20 blackbirds")
main()