Change Contents of the Bubble
Welcome to CS1315. Click on the python to add comments.

Looking for the book? They have it at the Engineer's Bookstore at 748 Marietta St NW. Here is there website: http://www.engrbookstore.com/ - Monica

Hotspots: Slides and CodeTA CornerComments?AnnouncementsFAQStatic Webspace
View this PageEdit this Page (locked)Uploads to this PageHistory of this PageHomeRecent ChangesSearchHelp Guide

Sp2004 Midterm 2 Review

Below are questions like those we plan to ask on Midterm #2 (March 26). The exam will consist of 4 or 5 questions like these.

Please do try these questions! Post your answers, questions, comments, concerns, and criticisms on the pages for each question. Those comments, questions, etc. can also be about each others' answers! If someone posts an answer that you don't understand, ask about it! If you see a question here that you know the answer to, don't keep it to yourself – help your fellow students!

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


Form Letter


The below function generates form letters of the kind that might appear as spam in an inbox near you.
def formletter(gender,lastName,city,eyeColor):
  file = open("formletter.txt","wt")
  file.write("Dear ")
  if gender=="F":
    file.write("Ms. "+lastName+":\n")
  if gender=="M":
    file.write("Mr. "+lastName+":\n")
  file.write("I am writing to remind you of the offer ")
  file.write("that we sent to you last week. Everyone in ")
  file.write(city+" knows what an exceptional offer this is!")
  file.write("(Especially those with lovely eyes of "+eyeColor+"!)")
  file.write("We hope to hear from you soon.\n")
  file.write("Sincerely,\n")
  file.write("I.M. Acrook, Attorney at Law")
  file.close()


When this is executed with formletter("M","Guzdial","Decatur","brown"), it generates:

Dear Mr. Guzdial:
I am writing to remind you of the offer that we sent to you last week. Everyone in Decatur knows what an exceptional offer this is!(Especially those with lovely eyes of brown!)We hope to hear from you soon.
Sincerely,
I.M. Acrook, Attorney at Law


Modify this program with one of the following:

Questions, comments, and answers for Midterm Exam 2 Review Spring 2004: Form Letter


Short Essay


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

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

(c) What is dot notation and when do you use it?

(d) Why is red a bad color to use for chromakey?

(e) What's the difference between a function and a method?

(f) 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?

(g) What are some advantages that Vector-Based graphics have over Bitmap Graphical representations (like JPEG, BMP, GIF)?


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


What's the underlying representation?


For each of the below, see if you can figure out the representation in terms of bits and bytes.

(a) Internet addresses are four numbers, each between 0 and 255. How many bits are in an Internet address?

(b) 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?

(c) 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?

(d) 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 2004: What's the underlying representation?


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?

(g) What is an ISP? Can you give an example of one?


Questions, comments, and answers for Midterm Exam 2 Review Spring 2004: Internet Questions


HTML Questions


(a) Define what each of the following tags do in HTML:

(b) What does HTML stand for ?

(c) What would the HTML look like to create the word "Hello" in an oversized, bold, italicized, and red font?

(d) What is XML?


Questions, comments, and answers for Midterm Exam 2 Review Spring 2004: HTML Questions


Sound Timing Questions


(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 Spring 2004: Sound Timing


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 Spring 2004: What do the programs do?


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 Spring 2004: Re-mixing the recipe


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:

FROMTO
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 Spring 2004: Encoding and Decoding


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 Spring 2004: Count 'em up


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"]
  phrases = phrases + ["very badly", "while skipping","instead of grading", "while typing on the CoWeb."]
  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 2004: Gendered random sentences


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 Spring 2004: Rainfall problem


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


Questions, comments, and answers for Midterm Exam 2 Review Spring 2004: Duplicate a List


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:

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"))
  addText(canvas,10,50,"This is not a picture")
  addLine(canvas,10,20,300,50)
  addRectFilled(canvas,0,200,300,500,yellow)
  addRect(canvas,10,210,290,490)
  return canvas



Questions, comments, and answers for Midterm Exam 2 Review Spring 2004: Graphics from a List


The Cover-Up


You have just been caught by the FBI for downloading illegal music. During your questioning though, you are left with the laptop that contains all the incriminating evidence. There are hundreds of log files in a single directory with your initials in the files. You need to replace all instances of your initials with some other inintials (like your professor's!) to throw the FBI off your case.

Remembering what you learned about listing jpeg files in a directory from hw4:
import os
...

for file in os.listdir(directory):
  if file.endswith(".txt")
    ... perform operations on the current file

And remembering how to open files for reading and writing:
myfile = open( fileNameAndLocation, "rt") #open file for reading
myfile = open( fileNameAndLocation, "wt") #open file for writing, clearing the contents of the file

And remembering the function replace(toFind, toReplaceWith) returns a modified string, you must write a function coverUp that takes in a directory name and replaces all instances of your initials in any ".txt" files with the initials of your professor!

Be sure to close close the files that you open!

Questions, comments, and answers for Midterm Exam 2 Review Spring 2004: The Cover-Up


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:

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")
  weather = file.read()
  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"



Questions, comments, and answers for Midterm Exam 2 Review Spring 2004: Address book functions


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")
>>> lines=file.readlines()
>>> print lines
['def littlepicture():\n', '  canvas=makePicture(getMediaPath("640x480.jpg"))\n', 
'  addText(canvas,10,50,"This is not a picture")\n', '  addLine(canvas,10,20,300,50)\n', 
'  addRectFilled(canvas,0,200,300,500,yellow)\n', '  addRect(canvas,10,210,290,490)\n', 
'  return canvas']
>>> file.close()

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


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


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 Spring 2004: Mirroring, Generalized #2


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 Spring 2004: Rewrite the Splice


Re-splicing the splice


Here is a sound Missing File (/cs1315/uploads/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 wordIndex where it stops in the sound
This7865
is27170
a40326
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 Spring 2004: Re-splicing the splice


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!


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




Links to this Page