View this PageEdit this PageAttachments to this PageHistory of this PageHomeRecent ChangesSearch the SwikiHelp Guide

Midterm Review 2

Short Essay


1. You write a program (a) when you want to communicate the PROCESS (how you got to the result) to someone else and (b) when you want the process to be REPLICABLE by others. Writing a program might be useful when one wants to take a bunch of numerical data and run it through a lengthy series of mathematical operations. So instead of using the existing calculator application to divide x by y, take the integer of the outcome, add five, etcetera, you just write a program that will do the task over and over again in one easy step. If illustrating process and facilitating mimicability isn't important, like for shrinking an image for a website, then Photoshop or another existing application are fine alternatives.

2. An array is a continuous line of elements that we have used to represent data in the form of sound and text. A matrix is a two-dimensional array, containing both width and height that we have used to represent pictures. Trees are elements that being with one "root"(such as C:\) and then split out into different “branches” called directories which eventually end in "leaves" or files. Any directory can contain more directories and files. We use trees when we want write a program that processes all of the files in a directory, for example when we labeled all of the photographs in a certain directory. Without trees it would be extremely tedious to alter multiple files at a time since you would have to specify the entire name of every file – the computer couldn’t just know that you want everything in a given directory. We have many different directories so that we can group similar things together to make them easier to locate. For example, if I had only one directory on my computer, I would have to search through every file on the machine to find the one file that I needed.

3. All data in Python are actually objects. A function is a recipe that tells the computer how to do something. Objects store data and they know certain special functions that only apply to their type of data. These special functions are called methods. To execute a method, you use dot notation. Dot notation is used to access certain capabilities of a file (module) that have been imported to a computer and contain additional functions and objects that JES originally did not. It is written as "module"."function". One example of dot notation is the capitalize method, which is known only to strings. It is written “string name”.capitalize.

4. Red is a bad color to use for chromakey because it is too often a dominant component in color. This is especially true with people because skin has many red tones to it. So when you set the color to be replaced as red, not only does the red background get replaced, so does some part of the people’s faces.

5. A function is recipe telling a computer how to do something. A method is a special type of function that only applies to a specific type of file. For example, capitalize is a method since it is a function that only applies to strings. For example, a jpeg file is a picture. How do you capitalize a picture? It doesn’t apply.

6. A file can be saved in many different directories within a disk (as more folders are created), which would be better represented by multiple paths (branches) off of the original disk (root) leading to the file (leaf). This is better than an array since an array is a continuous line of elements with no grouping, making it more tedious to search.

Count ‘em up


Write a function called countAs that will take a string as input. The string will contain only a's, b's, and c's, e.g., "abccbbaa" or "aaabbbccc". Count the number of a's in the input, and print the count.

def countAs(string):
count = 0
for letter in string:
if letter == "a":
count = count + 1
print count,"a's in the string"


Re-splicing the splice


Here is a sound thisisatest.wav ("This is a test."). The length of the sound is 64512 samples. Using MediaTools, I found the end points for each of the words in the sound:
Recorded word Index where it stops in the sound
This 7865
is 27170
a 40326
test. 55770
Here is a program to copy the word "Test" from the end of the sound to the front.

def spliceTest():
file = r"C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\thisisatest.wav"
source = makeSound(file)
target = makeSound(file) # This will be the newly spliced sound
targetIndex=1 # targetIndex starts at the beginning
for sourceIndex in range( 40327, 55770): # Where the word "Test" is in the sound
setSampleValueAt(target, targetIndex, getSampleValueAt( source, sourceIndex))
targetIndex = targetIndex + 1
play(target) #Let's hear and return the result
return target

Now write the reverse: Copy the word "This" in place of the word "Test" so that the sound says "This is a This." Assume that the sound file location is the same place as above. Make sure that none of the word "Test" remains – put zeroes in the samples after the word "This" to the end of the sound.

def spliceAgain(file):
source = makeSound(file)
target = makeSound(file)
targetIndex = 40236
for sourceIndex in range(1, 7865):
setSampleValueAt(target, targetIndex, getSampleValueAt(source, sourceIndex))
targetIndex= targetIndex + 1
for targetIndex in range(48191, 55770):
setSampleValueAt(target, targetIndex, 0)
targetIndex = targetIndex +1
play(target)
return target

Re-mixing the recipe


Take a look at the program below, then answer the questions:

def spliceWeird():
file = r"C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\thisisatest.wav"
source = makeSound(file)
target = makeSound(file) # This will be the newly spliced sound
targetIndex=1 # targetIndex starts at the beginning
  1. Loop A
for sourceIndex in range( 40327, 55770): # Where the word "Test" is in the sound
setSampleValueAt(target, targetIndex, getSampleValueAt( source, sourceIndex))
targetIndex = targetIndex + 1
  1. Loop B
for sourceIndex in range( 40327, 55770,2): # Where the word "Test" is in the sound
setSampleValueAt(target, targetIndex, getSampleValueAt( source, sourceIndex))
targetIndex = targetIndex + 1
  1. Loop C
for sourceIndex in range( 55770,40327,-2): # Where the word "Test" is in the sound
setSampleValueAt(target, targetIndex, getSampleValueAt( source, sourceIndex))
targetIndex = targetIndex + 1
  1. Loop D
for sourceIndex in range( 40327, 55770,2): # Where the word "Test" is in the sound
setSampleValueAt(target, targetIndex, getSampleValueAt( source, sourceIndex))
targetIndex = targetIndex + 1
  1. Loop E
for sourceIndex in range( 55770,40327,-2): # Where the word "Test" is in the sound
setSampleValueAt(target, targetIndex, getSampleValueAt( source, sourceIndex))
targetIndex = targetIndex + 1
  1. Loop F
for sourceIndex in range( 55770,40327,-1): # Where the word "Test" is in the sound
setSampleValueAt(target, targetIndex, getSampleValueAt( source, sourceIndex))
targetIndex = targetIndex + 1
play(target) #Let's hear and return the result
return target


1. What do each of the loops in the above program do? What does the final sound sound like?
2. Is there anything left in the sound when Loop F finishes? What is the value of targetIndex when the function ends?

1. The first is how it should sound, the second part is what the loop is actually doing.
Loop A: "test is a test"; inserts "test" at the beginning of the sound
Loop B: "test test a test"; inserts the word "test" after the first test, but twice as fast because it only takes every other sample
Loop C: "test test tset a test"; inserts "test" backwards after the second word “test”, but twice as fast as the original speed because it only takes every other sample
Loop D: "test test tset test test"; inserts the word “test” again after the last portion, only twice as fast because it only takes every other sample.
Loop E: "test test tset test tset test"; inserts "tset" after the last “test”, twice as fast because it only takes every other sample.
Loop F: "test test tset test tset tset"; inserts “tset” in place of the last “test”, only backwards and at normal speed.
So after all loops, the final sound will be “TEST test tset test tset TSET”. All caps denoted normal speed. Uncapitalized means it is at double speed.

2. The final value of targetIndex is 61775. I found this by doing 15443+7720+7720+7720+7720+15443-1. The -1 is because it started at 1, and the other values are found by just counting up the number of values in the given ranges.

Making sounds to order


Recall that we figured out how to generate sine waves and add them together, like this:
>>> f440=sineWave(440,2000)
>>> f880=sineWave(880,4000)
>>> f1320=sineWave(1320,8000)
>>> addSounds(f880,f440)
>>> addSounds(f1320,f440)
>>> play(f440)
>>> just440=sineWave(440,2000)
>>> play(just440)

You're to write a new function that will create a sound to order. Assume that the functions sineWave and addSounds are available to you. Write a function increasingAmplitude that will input a frequency freq and a starting amplitude ampl. Your function will then generate four sine waves:
(In sound terms, your new sound will have four partials, only the odd harmonics, and will have increasing amplitude among the harmonics.)
Be sure to return the resultant sound which is the sum of these four partials!

def increasingAmplitude(freq, ampl):
sound1=sineWave(freq,ampl)
sound2=sineWave(3&starfreq, 2&starampl)
sound3=sineWave(5&starfreq, 3&starampl)
sound4=sineWave(7&starfreq, 4&starampl)
addSounds(sound1, sound2)
addSounds(sound2, sound3)
addSounds(sound3, sound4)
play (sound4)
return sound4

Address book functions


Let's imagine that you have an address book file, named "address.txt", conveniently located in your JES folder (hint: You don't need a path to the file!) The format of the file looks like this:

Charlie Brown:1919 Peanuts Lane:Atlanta, GA:404-992-9292
Peppermint Patty:2020 Cashew Street:Atlanta, GA:404-299-2929
Calvin:101 Tiger Lane:Decatur, GA:770-899-8989

You are to write two functions:
• The first is called lookup that will accept a string as input that will be some part of a name to look up. You should print out the complete line of name, address, and phone-number for the matching person–if the person is found. If the person is not found, you should print "Not found."
• The second is called phone that will take the same input, but will print out JUST THE PHONE NUMBER and "Not found" if the input name is not found.

def lookup(name):
addressFile= "address.txt"
file = open (addressFile, "rt")
address = file.read()
file.close()
nameloc = address.find("name")
if nameloc != -1:
namebegin = address.rfind("\n", nameloc)
endaddress = address.find("\n", nameloc)
print address[namebegin+1:endaddress]
if nameloc == -1:
print "Not found"

def phone(name):
file = open("addresses.txt")
addresses = file.read()
file.close()
lines = addresses.split("\n")
numFound = 0
for line in lines:
lineData = line.split(":")
found = lineData[0].find(string)
if found != -1:
print lineData[3]
numFound = numFound + 1
if numFound == 0:
print "Not Found"

Gendered Random Sentences


Create a new sentence function that takes as input a single letter, "M" for Male or "F" for Female. If the input is "M", print a random sentence with a noun as the name of a known male. If the input is "F", print a random sentence with a noun as the name of a known female.

import random
def sentence(x):
nounsM = ["Mark", "Adam", "Larry", "Jose", "Matt", "Jim"]
nounsF = ["Angela", "Laura", "Meghan", "Mary"]
verbs = ["runs", "skips", "sings", "leaps", "jumps", "climbs", "argues", "giggles"]
phrases = ["in a tree", "over a log", "very loudly", "around the bush", "while reading the Technique"]
phrases = phrases + ["very badly", "while skipping","instead of grading", "while typing on the CoWeb."]
if x =="M":
print random.choice(nounsM), random.choice(verbs), random.choice(phrases)
if x=="F":
print random.choice(nounsF), random.choice(verbs), random.choice(phrases)

Graphics from a List


Write a function doGraphics that will take a list as input. The function doGraphics will start by creating a canvas from the 640x480.jpg file in the mediasources folder. You will draw on the canvas according to the commands in the input list.
Each element of the list will be a string. There will be two kinds of strings in the list:
• "b 200 120" means to draw a black dot at x position 200 y position 120. The numbers, of course, will change, but the command will always be a "b". You can assume that the input numbers will always have three digits.
• "l 000 010 100 200" means to draw a line from position (0,10) to position (100,200)
So an input list might look like: ["b 100 200","b 101 200","b 102 200","l 102 200 102 300"] (but have any number of elements).

def doGraphics(mylist):
canvas = makePicture(getMediaPath("640x480.jpg"))
for i in mylist:
if i[0] == "b":
x = int(i[2:5])
y = int(i[6:9])
print "Drawing pixel at ",x,":",y
setColor(getPixel(canvas, x,y),black)
if i[0] =="l":
x1 = int(i[2:5])
y1 = int(i[6:9])
x2 = int(i[10:13])
y2 = int(i[14:17])
print "Drawing line at",x1,y1,x2,y2
addLine(canvas, x1, y1, x2, y2)
return canvas

Duplicate a list


Write a function duplicateList to input a list and then duplicate each element of the list. If the input is [1,2,3] return [1,1,2,2,3,3]. (Use the above list examples to pull this off.)
Remember, input must be a list! So,

>>>list=[“1”,”5”,”6”,”7”,”3”,”2”]
>>>duplicateList(list)

def duplicateList(list):
newlist = []
for item in list:
newlist = newlist + [item] + [item]
return newlist

Mirroring, Generalized


a. Write a function to accept the filename of a sound, then return the sound mirrored around the midpoint of the sound, from front to back.

b. Write a second function to accept a string as input, the mirror the string from front to back. "abcdefghi" should be turned into "abcddcba"

def mirroring(file):
sound=makeSound(file)
mirrorpoint=int(getLength(sound)/2)
for sampleIndex in range(mirrorpoint+1,getLength(sound)):
value1 = getSampleValueAt(sound,mirrorpoint)
setSampleValueAt(sound,sampleIndex,value1)
mirrorpoint = mirrorpoint – 1

def mirror(string):
mirrorpoint=int(len(string)/2)
string1=string[0:mirrorpoint]
string2=""
for i in range(mirrorpoint, len(string)-1):
value1=string[mirrorpoint-1]
mirrorpoint=mirrorpoint-1
string2=string2+value1
print string1+string2

Reverse a File


Write a function reverseFile that inputs the name of a file, opens it, and then writes it out to a file in the JES directory with the lines reversed.
If the original file "original.txt" (assume, for now, in the directory JES) contains the lines:
This is
a perfectly
ordinary
file, okay?

Then calling reverseFile("original.txt") should create a file in the JES directory named reversed with the contents:
file, okay?
ordinary
a pefectly
This is

def reverseSimple(filename):
file = open(filename,"rt")
lines = file.readlines()
file.close()
newfile = "reversed.txt"
file = open("reversed.txt","wt")
lines.reverse()
for line in lines:
file.write(line+"\n")
file.close()

What’s the Underlying Representation?


For each of the below, see if you can figure out the representation in terms of bits and bytes.
1. Internet addresses are four numbers, each between 0 and 255. How many bits are in an Internet address?
2. In the programming language Basic, lines can be numbered, each one between 0 and 65535. How many bits are needed to represent a line number?
3. Each pixel's color has three components: Red, green, and blue, each of which can be between 0 and 255. How many bits are needed to represent a pixel's color?
4. A string in some systems can only be up to 1024 characters. How many bits are needed to represent the length of a string?
1. 4 numbers x 8 bits=32bits per address or 32/8=4bytes
2. 16 bits (2^n=65536, n=16)
3. Each RGB is 8bits, and three make 24bits or 3bytes
4. 10 bits (2^n=1024, n=10)

What Do the Programs Do?


def foo(a):
x = 0
y = 0
for i in a:
if i == "a":
x = x + 1
if i == "b":
y = y + 1
print y-x

a.What will this program print when you execute foo("abracadabra")? -3

b. Will this program work for lists with single character elements, e.g., foo(['a','b','c'])? Why or why not? No – treats each element as separate string.

def bar(sound):
s = ""
for i in range(1,100):
v = getSampleValueAt(sound,i)
if v > 0:
s = s + "+"
if v = 0:
s = s + "-"
print s

c. This function bar prints out a string, based on the samples in the sound. What does the string represent? String represents where the sound has positive and negative values. The positive samples are denoted by the plus sign. The negative and zero sample values are denoted by the negative sign.

d. How long (how many characters) will the output of this program be? 99 characters

The Rainfall Problem


Write a function rainfall that will input a list of numbers, some positive and some negative, e.g., [12, 0, 41, -3, 5, -1, 999, 17]. These are amounts of rainfall. Negative numbers are clearly a mistake. Print the average of the positive numbers in the list. (Hint: The average is the total of the positive numbers divided by the average of just the positive numbers.)

def rainfall(list):
x=0
y=0
for i in list:
if i>=0:
x= x + i
y= y + 1
print (x/y)

Extra credit (5 points): Write the function so that, if the number 999 appears in the list, add in no later numbers in the list. So, if the above example were input, the 17 would not be added into the average.

def rainfall2(list):
x=0
y=0
for i in list:
if i>=0:
x= x + i
y= y + 1
if i == 999:
break
print (x/y)