## Sp2003 Midterm Review 2

Below are questions like those I plan to ask on Midterm REMOVED (Feb. 14). The exam will consist of 4 or 5 questions like these.

1. If you don't post, neither will I. I will not be posting official solutions to these problems at all! If one of you gets it right, terrific!
2. I will try to always point out if an answer is wrong. I won't always point out when the answer is right.
3. I am glad to work with you toward the right answer. I will give hints, and I'm glad to respond to partial guesses.

### Short Essay

1. Give me one example of a task for which you would not write a program, and give me another example of a task for which you would write a program.
2. What's the differerence between an array, a matrix, and a tree? Give an example where we have used each to represent some data of interest to us.
3. What is dot notation and when do you use it?
4. Why is red a bad color to use for chromakey?
5. What's the difference between a function and a method?
6. Why is a tree a better representation for files on a disk than an array?

Questions, comments, and answers for Midterm Exam 2 Review Spring 2003: Short Essay

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

Remember that strings are sequences.
```>>> for i in "Hello":
...     print i
...
H
e
l
l
o
```

Questions, comments, and answers for Midterm Exam 2 Review Spring 2003: Count 'em up

### Re-splicing the splice

At the Feb. 7 class, we recorded the sound thisisatest2.wav ("This is a test."). The length of that sound is 64512 samples. Using MediaTools, we 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

We wrote a program in class 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.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)	        #REMOVEDt'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.

Questions, comments, and answers for Midterm Exam 2 Review Spring 2003: Re-splicing the splice

### Re-mixing the recipe

We've learned over the last few weeks that we can recombine recipes–in some ways, like how one can recombine physical, cooking recipes. A nice unit of recombining is a loop and its body.

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
# 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
# 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
# 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
# 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
# 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
# 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)	        #REMOVEDt'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?

Questions, comments, and answers for Midterm Exam 2 Review Spring 2003: Re-mixing the recipe

### 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)
>>> 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:
• The first will have frequency freq and amplitude ampl.
• The second will have frequency 3*freq and amplitude ampl*2.
• The third will have frequency 5*freq and amplitude ampl*3.
• The fourth will have frequency 7*freq and amplitude ampl*4.
(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!

Questions, comments, and answers for Midterm Exam 2 Review Spring 2003: Making sounds to order

### (Changing the problem slightly 1 May 2003)

REMOVEDt'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 REMOVED: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.

You might want to reference these two programs that we discussed in class, to look up DNA subsequences in a file, and to look up the temperature in a Web page.
```def findSequence(seq):
sequencesFile = getMediaPath("parasites.txt")
file = open(sequencesFile,"rt")
file.close()
# Find the sequence
seqloc = sequences.find(seq)
#print "Found at:",seqloc
if seqloc != -1:
# Now, find the ">" with the name of the sequence
nameloc = sequences.rfind(">",0,seqloc)
#print "Name at:",nameloc
endline = sequences.find("\n",nameloc)
print "Found in ",sequences[nameloc:endline]
if seqloc == -1:
```

```def findTemperature():
weatherFile = getMediaPath("AtlantaWeather1.html")
file = open(weatherFile,"rt")
file.close()
# Find the Temperature
humloc = weather.find("Humidity")
if humloc != -1:
# Now, find the "," where the temp starts
temploc = weather.rfind(",",0,humloc)
endline = weather.find("<",temploc)
print "Current temperature:",weather[temploc+1:endline]
if humloc == -1:
print "They must have changed the page format -- can't find the temp"

```

### Gendered random sentences

Remember the random sentence generator that we did in class?

```import random

def sentence():
nouns = ["Mark", "Adam", "Angela", "Larry", "Jose", "Matt", "Jim"]
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"]
print random.choice(nouns), random.choice(verbs), random.choice(phrases)

```

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.

Questions, comments, and answers for Midterm Exam 2 Review Spring 2003: Gendered random sentences

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

Recall that a list is manipulated like this:
```>>> mylist = ["This","is","a", 12]
>>> print mylist
['This', 'is', 'a', 12]
>>> print mylist[0]
This
>>> for i in mylist:
...       print i
...
This
is
a
12
>>> print mylist + ["Really!"]
['This', 'is', 'a', 12, 'Really!']
```

Lists also understand the function len for returning their length. You also need to know that the function int will convert a string that contains numbers into an integer. int("12") returns the number 12.

You know how to set pixel colors with setColor(getPixel(p,x,y),black). You might also want to recall:
```def littlepicture():
canvas=makePicture(getMediaPath("640x480.jpg"))
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.)

### 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
```

You may want to reference this example from class lecture:
```>>> file=open(program,"rt")
>>> print lines
['def littlepicture():\n', '  canvas=makePicture(getMediaPath("640x480.jpg"))\n',
'  return canvas']
>>> file.close()
```

(You'll also want the list functions described earlier.)

Questions, comments, and answers for Midterm Exam 2 Review Spring 2003: Reverse a file

### 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?

Questions, comments, and answers for Midterm Exam 2 Review Spring 2003: What's the underlying representation?