Spring 2005 Final Exam Review
Applying your knowledge
(I) Your mother shows you this cool new image processing program she bought. "I can finally get rid of red-eye!" When she clicks the red-eye removal button, she:
- Draws a circle with her mouse around the red area in the eye.
- Then clicks on a palette of colors of what the eye color should be.
- And all the red is replaced with the selected color.
She says, "How did that work? That's amazing. How can the computer figure out what part is red?" Answer your mother's questions,
(a) How did the red get replaced by the selected color? and
(b) how did the computer know what part was red?
(II) You have a new computer that seems to connect to the Internet, but when you try to go to http://www.cnn.com you get a "Not Found" error. You call tech support, and they tell you to try to go to http://64.236.24.20 That works.
Now both you and the Tech know what's wrong with your computer's settings. What isn't working properly since you can get to a site via the Internet but can't get the domain name www.cnn.com to be recognized?
(III) Your father calls you. "My tech support people are saying that the company website is down because the database program is broken. What does the database have to do with our company website?"
You explain to him how databases can be integral to running large websites.
Explain both:
(a) how the website comes to be authored through the database and
(b) how the HTML is actually created.
Questions, comments, and answers for Final Exam Review Spring 2005: Applying Your Knowlegde
Working with Classes
Imagine that you have a class Box like the below:
class Box:
def __init__(self):
self.setDefaultColor()
self.size=10
self.position=(10,10)
def setDefaultColor(self):
self.color = red
def draw(self,canvas):
addRectFilled(canvas,self.position[0],self.position[1],self.size,self.size,self.color)
(a) What will you see if you execute the below:
canvas = makeEmptyPicture(400,200)
joe = Box()
joe.draw(canvas)
repaint(canvas)
(b) Add a method to Box named setColor that takes a color as input, then makes the input color the new color for the box.
(c) Add a method to Box named setSize that takes a number as input, then makes the input number the new size for the box.
(d) Add a method to Box named setPosition that takes a list or tuple as argument, then makes that input the new position for the Box.
Now consider the below code added to the above:
class SadBox(Box):
def setDefaultColor(self):
self.color=blue
(e) What will you see if you execute the below:
jane = SadBox()
jane.draw(canvas)
repaint(canvas)
Questions, comments, and answers for Final Exam Review Spring 2005: Working with classes
Random Weather Comments
You're thinking about adding something to your HTML home page generator that will make random, relevant comments about the weather depending on the temperature.
- If it's going to be less than 32, you want to insert either "Watch out for ice!" or "Did I move North?!?"
- If it's going to be between 32 and 50, you want to insert either "I can't wait for winter to be over!" or "Come on, Spring!"
- If it's over 50 but less than 80, you want to insert either "It's getting warmer!" or "Light jacket or less weather."
- If it's over 80, you want to insert either "FINALLY! Summer!" or "Time to go swimming!"
Write a function named weathercomment that will take a temperature as input and return one of the phrases randomly. In other words, you want to use the temperature to decide which are the relevant phrases, then pick one randomly from there.
You might recall these programs from class and exam review as examples. The top one generates gendered sentences, and the bottom one uses return to return a sentence to be inserted into a homepage.
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)
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),"."
return random.choice(nouns)+" "+random.choice(verbs)+" "+random.choice(phrases)+"."
Questions, comments, and answers for Final Exam Review Spring 2005: Random Weather Comments
Handling an address book
Let's imagine that you are keeping track of all of your contacts in a file named contacts.txt in your JES directory. The format of the file is pound sign, name, colon, company, colon, phone number, colon, and key phrases that you want to remember about this contact. (You may assume that names, companies, phone numbers, and key phrases won't have colons in them.) The file might look like this:
#Calvin:Calvin & Hobbes:990-8979:Cartooning, tiger tamer, philosophy
#Luke:Skywalker Ranch:897-7765:Lightsaber battles, martial arts, philosopher
#Arthur:Camelot Inc.:453-8976:Holy grail seeker, sword puller, king
Write a function called contact that will take a keyword in a string as input. If that keyword is found in the contacts file, print the name, company, and phone number of the contact. If it is not found, print "Not Found". So, if you executed contact("king") for the above file, you would get printed out "Arthur:Camelot Inc.:453-8976"
You may want to use these programs from lecture as reference.
def findSequence(seq):
sequencesFile = getMediaPath("parasites.txt")
file = open(sequencesFile,"rt")
sequences = file.read()
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:
print "Not found"
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 Final Exam Review Spring 2005: Handling an address book
Questions on Objects
1. What's the difference between an instance and a class?
2. How are functions and methods different?
3. How is object-oriented programming different from procedural programming and functional programming?
4. What is Polymorphism?
5. What is Encapsulation?
6. What is Aggregation?
7. How did biological cells influence the development of the ideas of objects?
Questions, comments, and answers for Final Exam Review Spring 2005: Questions on Objects
Recursion
Remember this example:
>>> downUp("Hello")
Hello
ello
llo
lo
o
lo
llo
ello
Hello
Here's the code that we wrote that did it:
def downUp(word):
if len(word)==1:
print word #Print #1
return
print word #Print #2
downUp(word[1:])
print word #Print #3
a. Which print statement prints the ever-shortening ("on the way
down") words? Which print statement prints the single letter in the
middle? Which print statement prints the longer-growing words?
b. At most, how many copies of downUp are running at once with the
input "Hello"?
c. How would you modify downUp to create upDown that works like
this:
>>> upDown("Hello")
Hello
Hell
Hel
He
H
He
Hel
Hell
Hello
Questions, comments, and answers for Final Exam Review Spring 2005: Recursion
Crossword
Solve the crossword:

Across:
1. The property of methods that they can apply to more than one object.
2. A computational structure that has both data and behavior.
6. A property of objects that each holds its own data and behavior, that we can't reach inside another object.
9. What we call a function calling itself.
12. A specific function that takes a function as input and a list; it applies the function to each item of the list and returns just those items for which the input function returns true.
Down
1. An agreement for how two computers will interact; examples are HTTP and FTP.
4. A biological entity that scales well and is robust; a model for objects.
5. A network of networks based on a set of agreements.
7. A common language for database creation and manipulation.
8. A word that describes how objects can be combined (objects within objects) to create more complex structures.
10. A property of functions that are well-defined in such a way that the function does one and only one goal.
11. The address of something on the Web (abbreviation); Consists of a protocol, a server domain name, and the path to the page, image, or other object.
Questions, comments, and answers for Final Exam Review Spring 2005: Crossword
Questions on Databases
1. Name some characteristics of well-designed relational databases.
2. What is SQL?
3. What is a join?
Questions, comments, and answers for Final Exam Review Spring 2005: Questions on Databases
Questions on Functions
1. Identify three reasons why someone should use multiple functions rather than one big function in their programs.
2. What is procedural abstraction?
3. What is good modularity?
Questions, comments, and answers for Final Exam Review Spring 2005: Questions on Functions
Name that algorithm!
a. Consider these two programs.
def half(filename):
source = makeSound(filename)
target = makeSound(filename)
sourceIndex = 1
for targetIndex in range(1, getLength( target)+1):
setSampleValueAt( target, targetIndex, getSampleValueAt(source, int(sourceIndex)))
sourceIndex = sourceIndex + 0.5
play(target)
return target
and
def copyBarbsFaceLarger():
# Set up the source and target pictures
barbf=getMediaPath("barbara.jpg")
barb = makePicture(barbf)
canvasf = getMediaPath("7inX95in.jpg")
canvas = makePicture(canvasf)
# Now, do the actual copying
sourceX = 45
for targetX in range(100,100+((200-45)*2)):
sourceY = 25
for targetY in range(100,100+((200-25)*2)):
color = getColor(getPixel(barb,int(sourceX),int(sourceY)))
setColor(getPixel(canvas,targetX,targetY), color)
sourceY = sourceY + 0.5
sourceX = sourceX + 0.5
show(barb)
show(canvas)
return canvas
What algorithm is being implemented in these two examples? Explain
the algorithm in English.
B. Consider these two programs:
def findInSortedList(something, alist):
for item in alist:
if item == something:
return "Found it!"
return "Not found"
and
def turnRed():
brown = makeColor(57,16,8)
file = r"C:\Documents and Settings\Mark Guzdial\My Documents\\mediasources\barbara.jpg"
picture=makePicture(file)
for px in getPixels(picture):
color = getColor(px)
if distance(color,brown)<100.0:
redness=getRed(px)*1.5
setRed(px,redness)
show(picture)
return(picture)
What algorithm is being implemented in these two examples? Explain
the algorithm in English.
Questions, comments, and answers for Final Exam Review Spring 2005: Name that algorithim
Questions on Complexity
1. Who's Alan Turing and what did he do of interest to us?
2. Is optimization (e.g., the "song" problem) class P or
intractable? What does intractable mean?
3. Is the Traveling Salesman problem impossible to solve in
reasonable amounts of time?
4. What is a binary search? How do linear and binary searches
differ? In "Big-O" terms?
Questions, comments, and answers for Final Exam Review Spring 2005: Questions on Complexity
JavaScript
Recall this program from the JavaScript lecture:
<html>
<head>
<title>The Simplest Possible Web Page</title>
<script>
function countToTen()
{
document.write("<ul>");
for (i=1; i<= 10; i++)
{
document.write("<li>Item number: ",i,"</li>");
}
document.write("</ul>");
}
</script>
</head>
<body>
<h1>A Simple Heading</h1>
<p>This is a very simple web page.</p>
<p><img src="mediasources/barbara.jpg" />
</p>
<script> countToTen() </script>
</body>
</html>
Modify it to create a list of 100 entries just like this, starting at
100 and counting down to 1.
Questions, comments, and answers for Final Exam Review Spring 2005: JavaScript
Data structures
For each of the below data structures, define what it is, and write a small example that one can execute in a command area that uses that data structure.
- Array
- Matrix
- Tree
- List
- Hash Table
Questions, comments, and answers for Final Exam Review Spring 2005: Data Structures
Compilers, interpreters, and languages, oh my!
1. If you had a program written in C and you ran it through a C compiler, what would you expect to get out?
2. If you had a program written in Java and you ran it through a Java compiler, what would you expect to get out?
3. Why in the world would anyone want to use a virtual machine interpreter, and what does that have to do with programmable toaster ovens and cell phones?
4. What's a scripting language?
5. What is machine language? How does it differ from assembler language?
6. What does it mean for a language to be "interpreted"?
7. Why is that executing the same thing in JES and Photoshop is always faster in Photoshop?
Questions, comments, and answers for Final Exam Review Spring 2005: Coompilers, interpreters, and lnaguages, oh my!
More Recursion
Q. A misguided Python programmer wrote the following code to calculate factorial:
def fact(n):
retval = n * fact(n - 1)
if n == 1 or n == 0:
retval = 1
return retval
When he runs it nothing happens. Can you help him figure out what is wrong?
Q. What is the output of these programs
(Don't type them into JES, try and trace them!)
def one(string):
if len(string) == 1:
print string
return
print string
one(string[1:])
def two(string):
if len(string) == 1:
print string
return
two(string[1:])
print string
What does this do?
def mystery(string):
if string == "":
return 0
return 1 + mystery(string[1:]
What does this do?
# Please pass in an integer
def enigma(number):
if number == 0:
return 0
last = number % 10
rest = number / 10
return last + enigma(rest)
What does this do?
def puzzle(string):
if len(string) == 0:
return
print(string[0])
puzzle(string[1:])
What does this do?
def baffle(string):
if string = "":
return ""
return baffle(string[1:]) + string[0]
Questions, comments, and answers for Final Exam Review Spring 2005: More Recursion
Classes and Objects
When discussing classes and objects, classes are like
a. things you take for credit
b. blueprints or templates
c. instances
d. individuals
When discussing classes and objects, objects are instances of
classes and they
a. know things
b. can do things
c. know things and can do things
d. are mean to arrays
Which is NOT a characteristic of object oriented programming?
a. aggregation
b. encapsulation
c. noun oriented
d. procedural
Questions, comments, and answers for Final Exam Review Spring 2005: Classes and Objects
More coding
- Write a function called isEven that will return 1 (true) if a number passed in is even and 0 (false) if the number is odd.
- Write a function called isOdd that will return 1 (true) if a number passed in is odd and 0 (false) if the number is even.
- Imagine you have a function called isPrime which will be passed a number and will return 1 (true) if the number is prime (evenly divisable only by 1 and itself) and 0 (false) if it is not.
- What would be the result of
map(isPrime, [1,2,3,4,5,6,7,8,9,10])
filter(isPrime, [1,2,3,4,5,6,7,8,9,10])
- Compare and contrast the three programming paradigms we have studied this semester: Imperative, functional and object-oriented programming.
Questions, comments, and answers for Final Exam Review Spring 2005: More Coding
Concepts
- Explain (in some detail) how a large commercial wesite (e.g. news or catalog shopping) would use a database?
- Explain the purpose and function of the following items: URL, DNS, IP Address, Server, Client.
- Write a program called visine which will remove red eye. To do the best job what information would you like to have about the picture?
Questions, comments, and answers for Final Exam Review Spring 2005: Concepts
Even More Coding
- Write a function that will take in a string and will return the string only with every vowel appearing doubled i.e. 'Hi there!' would become 'Hii theeree!'
- Write a function that will eliminate all vowels from a string passed in i.e. 'Hi there!' would become 'H thr!'
Questions, comments, and answers for Final Exam Review Spring 2005: Even More Coding
Define
1. Explain digitizing media and its uses.
2. Give several examples of hardware and what each do and why they are important.
Questions, comments, and answers for Final Exam Review Spring 2005: Define
Links to this Page