## Fall2003 Midterm Review 2

Below are questions like those I plan to ask on Midterm REMOVED (Oct. 22). 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? Why do you have many directories on your disk, and not just one gigantic one?

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

### Count 'em up

(a) 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.

(b) Now, write a function to count the a's, b's, and c's, and print out ALL THREE counts.

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 Fall 2003: Count 'em up

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

Questions, comments, and answers for Midterm Exam 2 Review Fall 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)	        #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?

Questions, comments, and answers for Midterm Exam 2 Review Fall 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 Fall 2003: Making sounds to order

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 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 phone book information, and to look up the temperature in a Web page.
```def phonebook():
return """
Mary:893-0234:Realtor:
Fred:897-2033:Boulder crusher:
Barney:234-2342:Professional bowler:"""

def phones():
phones = phonebook()
phonelist = phones.split('\n')
newphonelist = []
for list in phonelist:
newphonelist = newphonelist + [list.split(":")]
return newphonelist

def findPhone(person):
for people in phones():
if people[0] == person:
print "Phone number for",person,"is",people[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 Fall 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
```

Questions, comments, and answers for Midterm Exam 2 Review Fall 2003: Graphics from a List

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

### Mirroring, Generalized

Remember how we mirrored a picture?
```def mirrorHorizontal(source):
mirrorpoint = int(getHeight(source)/2)
for y in range(1,mirrorpoint):
for x in range(1,getWidth(source)):
p = getPixel(source,x,y+mirrorpoint)
p2 = getPixel(source,x,mirrorpoint-y)
setColor(p2,getColor(p))
```

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"

Questions, comments, and answers for Midterm Exam 2 Review Fall 2003: Mirroring, Generalized

### 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 Fall 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 Fall 2003: What's the underlying representation?

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

b. Will this program work for lists with single character elements, e.g., foo(['a','b','c'])? Why or why not?

```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?
d. How long (how many characters) will the output of this program be?

Questions, comments, and answers for Midterm Exam 2 Review Fall 2003: What do the programs do?

### 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 total of just the positive numbers.)

You may want to recall these examples from lecture on how to manipulate lists:
```>>> 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!']
```

Try writing 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.

Questions, comments, and answers for Midterm Exam 2 Review Fall 2003: Rainfall problem

### Rewrite the Splice

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

(a) Rewrite this program so that the for loop changes the targetIndex and it's sourceIndex that's increment in the body of the loop.

(b) Now rewrite the original program where you copy the word "Test" to take up half as much space.

(c) Now rewrite the original program where you copy the word "Test" to take up twice as much space.

Questions, comments, and answers for Midterm Exam 2 Review Fall 2003: Rewrite the Splice

### Sound Timing

(a) How would you figure out the index of where the third second starts in a sound?

(b) Write a program that takes a sourceSound and a targetSound as input, then copy the sourceSound starting at 1 second and ending at 1.5 second into the targetSound starting 2 seconds into the targetSound.

(c) Write a program where you move one second of an input sound from the 4th second of the sound to the start of the 2nd second.

Questions, comments, and answers for Midterm Exam 2 Review Fall 2003: Sound Timing

### Encoding and Decoding

Remember the string method replace().

```>>> letter="Mr. Mark Guzdial requests the pleasure of your company at..."
>>> print letter.replace('a','!')
Mr. M!rk Guzdi!l requests the ple!sure of your comp!ny !t...
>>> print letter.replace('a','!').replace("e","#")
Mr. M!rk Guzdi!l r#qu#sts th# pl#!sur# of your comp!ny !t...
```

(a) Write a function to encode an input string so that vowels and key consonants are replaced with symbols, using this table:

 FROM TO e # i ! a @ o % u ^ r - s = t :

(b) Write a second function that takes an encoded string as input, and returns the original unencoded string.

Questions, comments, and answers for Midterm Exam 2 Review Fall 2003: Encoding and Decoding

### Internet Questions

(a) What's a Domain Name Server? What does it do?

(b) What are FTP, SMTP, and HTTP? What are they each used for?

(c) What is HyperText?

(d) What's the difference between a client and a server?

(e) How does knowing how to manipulate text help you in gathering and creating information on the Internet?

(f) What is the Internet?

Questions, comments, and answers for Midterm Exam 2 Review Fall 2003: Internet Questions