0% found this document useful (0 votes)
121 views31 pages

Introduction To Computing and Programming in Python 4th Edition Solution Manual

This document is a solution manual for the 4th edition of 'Introduction to Computing and Programming in Python' by Mark J. Guzdial and Barbara Ericson. It includes answers to various exercises related to computing concepts, encoding, and notable figures in computer science. The manual provides a structured index and detailed explanations for each question, emphasizing the intersection of computing with various fields and the historical context of computer science advancements.

Uploaded by

oe8cdye7ed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views31 pages

Introduction To Computing and Programming in Python 4th Edition Solution Manual

This document is a solution manual for the 4th edition of 'Introduction to Computing and Programming in Python' by Mark J. Guzdial and Barbara Ericson. It includes answers to various exercises related to computing concepts, encoding, and notable figures in computer science. The manual provides a structured index and detailed explanations for each question, emphasizing the intersection of computing with various fields and the historical context of computer science advancements.

Uploaded by

oe8cdye7ed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Solution Manual + Answer Key

Solution Manual for Introduction to Computing and Programming


in Python 4th Edition by Mark J. Guzdial Barbara Ericson

View Full Product:


https://selldocx.com/products/solution-manual-introduction-to-computing-and-pr

Book Title: Introduction to Computing and Programming in Python

Edition: 4th Edition

Author: Mark J. Guzdial Barbara Ericson

Click above to view a sample


Solutions Manual for
Introduction to Computing and
Programming in Python: A Multimedia
Approach, 4th Edition
By Mark J. Guzdial and Barbara Ericson

Solutions manual by Matthew Guzdial

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Index
Chapter 1- Page 1
Chapter 2- Page 7
Chapter 3- Page 14
Chapter 4- Page 21
Chapter 5- Page 29
Chapter 6- Page 40
Chapter 7- Page 64
Chapter 8- Page 70
Chapter 9- Page 83
Chapter 10- Page 101
Chapter 11- Page 145
Chapter 12- Page 157
Chapter 13- Page 168
Chapter 14- Page 185
Chapter 15- Page 200
Chapter 16- Page 206
Chapter 17- Page 213

Chapter 1
1.1 Every profession uses computers today. Use a Web browser and a search engine like
Google to find sites that relate your field of study with computer science or computing or
computation. For example, search for “biology computer science” or “management
computing.”

A good answer should have at least 2-3 links. For example, for “biology” some good
links would be:

http://www.brown.edu/research/projects/computational-molecular-biology/
http://www.sciencedirect.com/science/article/pii/S0960982201000811
http://www.biomedcentral.com/1471-2105/12/120

1.2 The 2013 Nobel Prize in Chemistry was in some sense a Nobel Prize given for work
in computer science. What was the role of computers in that Nobel Prize?

Computers were used to simulate the behavior of large molecules in a brand new way
combining classical and quantum physics.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


(Source: http://www.nobelprize.org/nobel_prizes/chemistry/laureates/2013/press.html)

1.3 Text characters are encoded in different ways. The bottom level is always binary in
bytes, but a different binary pattern can be used to represent different characters. Two of
these encodings are ASCII and Unicode. See if you can do Web searches on ASCII and
Unicode. What’s the difference between ASCII and Unicode? Why would we need
Unicode if we already had ASCII?

The major difference between ASCII and Unicode is the amount of characters both hold.
ASCII has 128 characters, while Unicode has over 110,000 characters. Unicode is largely
used for non-Latin letters, such as Chinese characters,

(Sources: http://en.wikipedia.org/wiki/ASCII and http://en.wikipedia.org/wiki/Unicode)

1.4 Consider the representation for pictures described in Section 1.4, where each dot
(pixel) in the picture is represented by three bytes, for the red, green, and blue
components of the color at that dot. How many bytes does it take to represent a 640 by
480 picture, a common picture size on the Web? How many bytes does it take to
represent a 1024 by 768 pictures, a common screen size? (What do you think is meant
now by a “three megapixel” camera?)

Bytes for 640 by 480 picture: (640*480)*3 = 921,600


Bytes for a 1024 by 768: (1024*768)*3 = 2,359,296

A “three megapixel” camera means that the camera can capture images with three million
pixels.

1.5 One bit can represent 0 or 1. With two bits you have four possible combinations 00,
01, 10, and 11. How many different combinations can you make with four bits or eight
bits (one byte)? Each combination can be used to represent a binary number. How many
numbers can you represent with 2 bytes (16 bits)? How many numbers can you represent
with four bytes?

Four bits: 16 combinations (0000, 0001, 0010, 0100, 1000, 0011, 0110, 1100, 0101,
1010, 1001, 0111, 1110, 1101, 1011, 1111)
Eight bits: 256 combinations
Two bytes/16 bits: 65,536 combinations
Four bytes/32 bits: 4,294,967,296 combinations

1.6 Microsoft Word used to use an encoding of a word-processing document called


“DOC.” Most recent versions of Microsoft Word use a different encoding called
“DOCX.” What’s the difference between them?

The “DOC” encoding was a unique encoding to Microsoft, while the “DOCX” encoding
is based on XML, the Extendable Markup Language. This makes it easier for other
programs to parse “DOCX” documents, along with conferring a number of other benefits

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


(such as smaller size, higher quality images, and a lower chance of file corruption).

(Source: http://www.inc.com/software/articles/201002/doc.html and


http://www.thebookdesigner.com/2013/04/docx-vs-doc/)

1.7 One of the powerful ideas in computer science is that encodings can be layered. Most
of the encodings we’ve talked about so far (e.g., pixels in a picture, characters, floating
point numbers) are based on binary. XML is a way of encoding information in text, which
is in turn encoded in binary. What are the advantages and disadvantages of using XML
rather than binary encodings?

Advantages:
-XML is easy for humans and computers to read.
-XML is easily extendible
-XML has been rapidly adopted by industry
Disadvantages:
-XML takes up more space than binary encoding
-XML is extendible and therefore not as standardized

(Source: http://www.mulberrytech.com/papers/HowAndWhyXML/slide009.html )

1.8 How can you encode a floating-point number in terms of bytes? Do a search on the
Web for “floating point.” You will find that there are different encodings of floating point
numbers. Take a common one like the IEEE Floating Point Standard as an example.
Assuming single precision, what is the largest and smallest numbers that you can
represent in that encoding?
A computer can represent a floating-point number as it would an integer number, but
with some extra information. Specifically, to be able to define the decimal portions of a
floating point, a computer must know an extra integer to raise 10 by to multiply the base
integer by. For example, if one was to represent the number 0.5 it would hold track of the
number 5 and -1, since 0.5 equals 5 x10^(-1).

Smallest number: 1x10-101


Largest number: 9999999x1090

(Source: http://www.wikipedia.org/wiki/IEEE_floating_point)

1.9 As we said in the chapter, computer science is about people. Start your exploration of
computer science by exploring the people who are computer scientists and influence
computer science. As you do, find Web sites that you believe are credible for your
information, and include the URL in your answers—with your reasons for believing that
source is credible. What general rules do you use to determine what is a credible Web
site?

Note: This question can be potentially confusing. Due to its structure, multiple

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


interpretations are possible. There are essentially two sections, the first implicitly asking
students to find people involved in computer science (and include the credible URL
where they found them). The second part asks how to determine if a Web site is credible.

Some examples of people involved in computer science (and links):


-Mark Guzdial (http://www.cc.gatech.edu/fac/mark.guzdial/)
-Anita Borg (http://anitaborg.org/)
-Bill Gates, Mark Zuckerberg, and Susan Wojcicki
(http://www.mercurynews.com/business/ci_24308090/code-org-mark-zuckerberg-bill-
gates-teach-computer-science-every-school )

Ways to determine if a link is credible:


-If it ends with a “.edu”
-If the link is a primary website for an organization or individual
-If the link references other credible web sites

1.10 Look up Alan Kay, object-oriented programming, and the Dynabook on the Web.
Alan is one of the inspirations for the media computation approach that we use in this
book. Can you figure out what he has to do with media computation?

There are several potential answers to this question:


-Alan Kay is considered one of the fathers of object oriented programming, which is used
exclusively in this book (Source:
http://amturing.acm.org/award_winners/kay_3972189.cfm)
-Alan Kay is invested in educating all people in computer science (Source:
http://www.vpri.org/)
-Perhaps the best answer, Alan Kay is interested in making use of media-rich
environments to teach computer science (Source: http://www.squeakland.org/)

1.11 Look up Clarence (Skip) Ellis. Without him, Google Docs wouldn’t work the way
that they do to help people collaborate. What did he do?

Clarence Ellis is considered one of the pioneers of operational transformation, which


deals with collaborative systems, such as those now used in Google Docs to allow for
multi-user editing. (Source: https://cs.illinois.edu/news/memory-clarence-ellis-1943-
2014)

1.12 Look up Grace Hopper on the Web. How did she contribute to programming
languages?

Grace Hopper created the first compiler for a computer programming language and
coined the term “debugging” for fixing computer flitches. (Source:
http://en.wikipedia.org/wiki/Grace_Hopper#cite_note-Booss03-6)

1.13 Look up Andrea Lawrence on the Web. What computer science department did she
chair?

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Andrea Lawrence chaired the computer and information sciences department of Spelman
University (Source: http://www.thehistorymakers.com/biography/andrea-lawrence-42)

1.14 Look up Alan Turing on the Web. What does he have to do with our notion of what
a computer can do and how encodings work?

Alan Turing created the definition for a modern computer in terms of what it can do,
referred to as a “Turing Machine”. Additionally, he came up with a means of encoding an
action table of a Turing machine as a string, such that someone can feed in instructions to
a machine and get an output back. (Source:
http://en.wikipedia.org/wiki/Universal_Turing_machine)

1.15 Look up Adele Goldberg on the Web. How did she contribute to programming
languages?

She was a forerunner or pioneer in a number of now common facets of programming


languages, including design patterns, object-oriented programming, and graphical user
interfaces. (Source:
http://en.wikipedia.org/wiki/Adele_Goldberg_%28computer_scientist%29)

1.16 Look up Kurt Gödel on the Web. What amazing things did he do with encodings?

He created Gödel numbering, a means by which a sequence of symbols can be


represented as natural numbers (Source:
http://en.wikipedia.org/wiki/G%C3%B6del_numbering)

1.17 Look up Ada Lovelace on the Web. What amazing things did she do before the first
mechanical computer was built?

Ada Lovelace was the first ever computer programmer, before the first computer was
even built, having come up with a stepwise sequence of operations for solving
mathematical problems. (Source: http://www.computerhistory.org/babbage/adalovelace/)

1.18 Look up Claude Shannon on the Web. What did he do for his master’s thesis?

Claude Shannon proved in his master’s thesis that Boolean algebra could be used to
simplify relays used in the electromechanical phone exchanges of the day, and later
defined digital circuit design. (Source:
http://dspace.mit.edu/bitstream/handle/1721.1/11173/34541425.pdf?sequence=1)

1.19 Look up Richard Tapia on the Web. What has he done to encourage diversity in
computing?

Richard Tapia directed or co-directed more minority and women doctoral candidates in
science and engineering than anyone in the country and has lead numerous programs to
increase diversity in the fields of science and engineering. (Source:
http://tapiaconference.org/about/tapia)

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


1.20 Look up Marissa Mayer on the Web. What computer tool (that you probably use
regularly) did she help create?

She helped to create Google’s now famous unadorned search page, along with the look
and feel of some of the company’s most popular products. (Source:
http://dealbook.nytimes.com/2012/07/16/googles-marissa-mayer-tapped-as-yahoos-
chief/?hp)

1.21 Look up Shafi Goldwasser on the Web. What major computing prize did she win in
2012 and why?

The ACM Turing Award, which she won for work in the theoretic foundations for the
science cryptography and pioneered new ways to check mathematical proofs. (Source:
http://amturing.acm.org/award_winners/goldwasser_8627889.cfm)

1.22 Look up Mary Lou Jepsen on the Web. What new technology is she working on?

She is working on small screens that can seamlessly join together like legos to create
larger screens, along with wall screens. (Source:
http://www.fastcodesign.com/3036692/fast-feed/google-is-inventing-screens-that-snap-
together-like-lego)

1.23 Look up Ashley Qualls on the Web. What did she create that is worth a million
dollars?

She created a website as a teenager that offered free MySpace account designs, making
thousands of dollars from ad revenue alone. (Source:
https://web.archive.org/web/20080220145135/http://potw.news.yahoo.com/s/potw/52250
/teen-millionaire)

1.24 Look up Tim Berners-Lee on the Web. What did he invent?

He implemented a communication protocol (Hypertext Transfer Protocol [HTTP]) that


allowed for client and server communication via the Internet, thereby inventing the
World Wide Web. (Source: http://www.w3.org/People/Berners-Lee/)

1.25 As in every field, people in computer science build on one another’s work.

. Who invented the Logo Turtle?

Paul Wexelblat built the first turtle (Source:


http://web.archive.org/web/20090310020335/http://www.erzwiss.uni-
hamburg.de/Sonstiges/Logo/logofaqx.htm#FAQ2)

. Who used the Logo Turtle to have fourth graders learn about fractions in mathematics?

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


There are multiple answers to this question, including Idit Harel, or Yasmin B. Kafai.
(Source: http://investigations.terc.edu/library/bookpapers/research_on_logo.cfm)

. Who invented a programming language that featured thousands of Logo Turtles in


order to model complex behavior like ants and termites?

Uri Wilensky authored NetLogo, which allows for simulation and modeling of ant
behavior and more. (Source: http://ccl.northwestern.edu/netlogo/index.shtml)

1.26 Now trace this series of who built on whose work.

. Who invented the laser printer?

Gary Starkweather invented the laser printer. (Source:


http://xenia.media.mit.edu/~yarin/laser/laser_printing.html)

. One of the winners of the ACM Turing Award (the closest that computer science has to
a Nobel Prize) invented a computer system for typesetting books on a laser
printer. Who was that?

Donald Knuth built a system (referred to as TeX) to computationally typeset


books for a laser printer.
(Source: http://amturing.acm.org/award_winners/knuth_1013846.cfm)

. The winner of a recent ACM Turing Award built a computer system on top of the last
typesetting system, to make it easier to use (but that’s not what he won the Turing
Award for). Who was that, and what did he win his award for?

Leslie Lamport developed the LaTeX system written on top of TeX. He won his
Turing Award in 2013 for contributions to distributed and concurrent systems,
essentially when several computations are executed simultaneously, potentially
interacting.
(Source: http://amturing.acm.org/award_winners/lamport_1205376.cfm)

Chapter 2
2.1

What is an algorithm?

Algorithm: A description of a process in a step-by-step manner, not tied to any


programming language. The same algorithm may be implemented in many different
languages in many different ways in many different programs—but they would all be the
same process if we’re talking about the same algorithm. (Chapter 1, Page 9)

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


What is an encoding?

Encoding: The means by which computers convert information into a particular form, for
example, from bytes to numbers to text. Note, the book does not contain an explicit
definition of encoding, but the two important things to get across are 1) the encoding’s
use in translating between different types of information and 2) tat the computer makes
use of multiple layers of encoding. (Chapter 1, Page 10)

What is the difference between an algorithm and a program?

A program is just one possible implementation of an algorithm within one computer


language. The same algorithm can be expressed in many different languages in many
different ways in many different programs. (Chapter 1, Page 9)

2.2

How can computers represent pictures as numbers?

Each image is composed of tiny dots called pixels, each composed of a sum of red, green,
and blue. The red, green, and blue values of a pixel are each represented as a byte; bytes
can then be represented as a number. (Pixel Information: Chapter 1, Pages 11-12; Byte
Information: Chapter 1, Pages 9-10)

How can computers represent text as numbers?

Computers can represent text via ASCII (American Standard Code for Information
Interchange) encoding. Using this encoding, the number 65 is interpreted as the capital
letter A, 66 is interpreted as the capital letter B, and so on. Each individual character of a
piece of text can then become a collection of numbers. (Chapter 1, Page 10)

Remember that the computer can only represent integer numbers in raw binary. How can
computers represent floating-point (decimal) numbers?

A computer can represent a floating-point number as it would an integer number, but


with some extra information. Specifically, to be able to define the decimal portions of a
floating point, a computer must know an extra integer to raise 10 by to multiply the base
integer by. For example, if one was to represent the number 0.5 it would hold track of the
number 5 and -1, since 0.5 equals 5 x10^(-1). Note: This is not explained in the book, but
Chapter 1, Question 1.8 suggests looking up IEEE floating point encoding that represents
floating-points in this way. wikipedia.org/wiki/IEEE_floating_point has a good write-up
of this approach.

2.3 What does def mean? What does the statement def someFunction(x,y): do?

The keyword “def” is used by Python to define new functions. The statement defines a
function with the title “someFunction” and the inputs “x” and “y”. The code directly after
this function header will be executed when the function is called. (Chapter 2, Page 34)

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


2.4 What does print mean? What does the statement print a do?

The keyword “print” means “Display a readable representation of whatever follows.”


(Chapter 2, Page 23)
The statement “print a” will do different things depending if “a” is a defined variable or
not. If it is, Python will print the value of that variable in a readable form. So if a = 5, the
number 5 will be printed to the console. If the variable “a” is not defined, Python will
print:

A local or global name could not be found. You need to define the function or variable
before you try to use it in any way.

(Chapter 2, Pages 24-25)

2.5 What is the output from print 1 / 3? Why do you get this output?

0. You get this output as both 1 and 3 are assumed to be integer numbers by Python.
Since integer numbers only allow for whole numbers, the answer to “How many times
does 3 go into 1” is “0”.

2.6 What is the output from print 1.0 / 3? Why do you get this output?

0.3333333333333333. You get this output as Python recognized 1.0 as a floating point
number, meaning that it allows for a decimal number answer, the same you would get on
a calculator.

2.7 What is the output from print 10 + 3 * 7? Why do you get this output?

31. You get this output as Python follows the order of operations, such that multiplication
(3*7=21) occurs before addition (10+21).

2.8 What is the output from print (10 + 3) * 7? Why do you get this output?

91. You get this output as Python follows the order of operations, such that calculations
within parenthesis occur before multiplication.

2.9 What is the output from print "Hi" + "there"? Why do you get this output?

Hithere. You get this output as Python implements addition between str types (strings) by
concatenating the second str on to the first.

2.10 What is the output from print "Hi" + 10? Why do you get this output?

The error value is: cannot concatenate 'str' and 'int' objects
Inappropriate argument type.
An attempt was made to call a function with a parameter of an invalid type. This means
that you did something such as trying to pass a string to a method that is expecting an
integer.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


You get this output as Python does not have a standard way to add or concatenate an int
(integer) onto a str (string).

2.11 What is the output from print "Hi" * 10? Why do you get this output?

HiHiHiHiHiHiHiHiHiHi

You get this output as Python recognizes multiplying a str (string) by an int (integer) as a
desire to repeat that str the number of times represented by the int.

2.12 What is the output from print "Hi" + "there"? Why do you get this output?

Note: This is a repeat of 2.9

2.13 What is the output from print "Hi" * "10"? Why do you get this output?

The error value is: can't multiply sequence by non-int of type 'str'
Inappropriate argument type.
An attempt was made to call a function with a parameter of an invalid type. This means
that you did something such as trying to pass a string to a method that is expecting an
integer.

You get this output as Python has no standard way to multiply two str types (strings)
together.

2.14 What is the output from print "Hi" + "10"? Why do you get this output?

Hi10
You get this output as, while “10” may seem to be a number the symbol “ on both sides
indicate that is a str type variable (string). As such, python simply concatenates it to the
end of “Hi”.

2.15 What does show(p) do? (Hint: There’s more than one answer to this question.)

If p is defined as a variable, then Python will print to the console the value of p. If p has
no value, Python will print out:

A local or global name could not be found. You need to define the function or variable
before you try to use it in any way.

(Chapter 2, Pages 24-25)

2.16 What is the output from the following? 


>>> a = 3
>>> b = 4
>>> x = a * b
>>> print x

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


12

2.17 What is the output from the following? 


>>> a = 3
>>> b = -5
>>> x = a * b
>>> print x

-15

2.18 What is the output from the following? 


>>> a = 3
>>> b = -5
>>> a = b
>>> b = 22
>>> x = a * b
>>> print x

-110

2.19 What is the output from the following? 


>>> a = 4
>>> b = 2
>>> x = a / b
>>> print x

2.20 What is the output from the following? 


>>> a = 4
>>> b = 2
>>> x = b - a
>>> print x

-2

2.21 What is the output from the following? 


>>> a = -4
>>> b = 2
>>> c = abs(a)
>>> x = a * c
>>> print x

-16

2.22 What is the output from the following?


>>> name = "Barb"
>>> name = "Mark"

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


>>> print name

Mark

2.23 What is the output from the following? 


>>> first = "Abe"
>>> last = "Lincoln"
>>> print first + last

AbeLincoln (Note: No space should exist in the outputted string)

2.24 What is the output from the following? 


>>> first = "Abe"
>>> last = "Lincoln"
>>> print first + “ “ +last

Abe Lincoln

Abe Lincoln (Note: There should be a space between Abe and Lincoln)

2.25 What is the output from the following? 


>>> first = "Abe"
>>> last = "Lincoln"
>>> swap = first
>>> first = last
>>> last = swap
>>> print first + " " + last

Lincoln Abe

2.26 What is the output from the following? 


>>> a = ord("A")
>>> b = 2
>>> x = a * b
>>> print x

130. Note: The function ord returns the integer value of a character using ASCII
encoding. In this case that value is 65.

2.27 What is being computed by the following?

The program is computing the time in seconds, minutes, and weeks that it would take a
turtle to travel from Miami to Seattle at the “turtleSpeed” rate. In this case, 0.5 m/s

2.28 What is being computed from the following?

The program is computing the escape velocity required to leave the earth’s gravity.
Changing the gravity, earthMass, or earthRadius values could allow you to calculate the

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


value for another planet.

2.29 What is being computed from the following?

The amount of time it would take to fall to the ground from the top of a building with
heightInStories stories and with each story feetPerStory tall.

2.30 The following code gives the error message shown below. Fix the code.

The issue is that the call to the method “pickAFile()” is case-sensitive, such that the call
to “pickafile()” will not be registered as the same thing. Therefore, the A and F should be
capitalized.

(Chapter 2, Page 26)

Note: There may be some confusion as to what the question refers to. A student could
potentially misunderstand and believe there is no code to be fixed or that they should
define a new method called “pickafile”. However, if the student read the chapter, it
should be obvious what to do.

2.31 The following code gives the error message shown below. Fix the code.

The problem is that the variable “d” is not defined. Therefore, all that has to be done is to
define d to something such that it can be multiplied by 3 (the value of “a”). It could then
be either any sort of number or even a string. For example:
>>> a = 3
>>> b = 4
>>> d = 4
>>> c = d * a
>>> c
12

OR

>>> a = 3
>>> b = 4
>>> d = “HI”
>>> c = d * a
>>> c
‘HIHIHI’

2.32

What happens if you multiply a number by a string, like 3 * "Hello"?

‘HelloHelloHello’ is outputted

What happens if you try to multiply a string by a string, "a" * "b"?

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


You get the error message:
The error value is: can't multiply sequence by non-int of type 'str'
Inappropriate argument type.
An attempt was made to call a function with a parameter of an invalid type. This means
that you did something such as trying to pass a string to a method that is expecting an
integer.

2.33

But what is the name pickAFile anyway?

The name pickAFile is used to tell Jython to run the code within the pickAFile method.
Note: It points Jython to that section of code, and this type of variable is thus sometimes
called a “function pointer”.

What do you get if you print pickAFile?

<function pickAFile at 0x21>

How about print makePicture?

<function makePicture at 0x22>

What prints, and what do you think it means?

Note: This section of this question is intentionally open-ended and a student should not
be expected to know at this point. What it actually means is the section of memory where
the function pointer is defined.

2.34

Try running the code below. What is the result?

Why did you get that? (Hint: “becomes the name for the value of.”)

The console prints out 5 as the variable myFunc is now the same value as the variable
abs. In this case, myFunc is now equivalent to the absolute value function, which returns
the absolute value of -5.

Chapter 3
3.1 You are running a bingo game where you want to tweet the winner of each round of
the game. You want to announce the name of who won, and how much they won in
dollars. Make a function that takes those two words in as input, and then announces the

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


win. For now, just print the statement that you will want to tweet later. (Hint: Remember
that you are taking a number as input, which has to be converted to a string to
concatenate it.)

def bingo(name, amount):


amountStr = str(amount)

print name + “ called Bingo! winning $”+amountStr

Note: Information on the function “str” in Chapter 3, Page 46. Students may choose
different variable names.

3.2 You are a race official on an ultra marathon (100 miles), and you want to display the
number and elapsed time for each runner on a big display. Write a program to generate
the phrase for the display based on the runner number, the mile marker, and the elapsed
time.

def runner(runnerNumber, marker, elapsedTime):


runnerStr = str(runnerNumber)
markerStr = str(marker)

print “Runner #”+runnerStr+” passed mile “+markerStr+” at time “+elpasedTime

3.3 The pyramid function in this chapter doesn’t quite line up with “=” character as input.
Try some others, like “n” and “m” and “t”. The last one seems to line up best. Why?

The character “t” lines up best as it’s the closest in width to the space character. All the
other characters look lopsided because they are much wider, meaning they extend far
more to the right than they should to make the pyramid even.

3.4 Create a function like the pyramid function that does the upside-down version. Your
function invertedPyramid should also take an input character and print an inverted
pyramid.

def invertedPyramid(char):
space = " "
print 9*char
print space ,7*char
print 2*space ,5*char
print 3*space ,3*char
print 4*space,char

3.5 Using for loops and using the same techniques as the pyramid function, create a
textsquare function that takes in two values as input: the character to use in making the
square, and the size of the square in characters. Then print out a square of that many
characters.

def textsquare(char, size):

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


space = " "

for index in range(size):


line = char+space*(size-2)+char
if index==0:
line= char*size
if index==size-1:
line= char*size
print line

Note: This is a tricky question, with many potential solutions. The important thing to
watch out for is that the printed square is just outlined in the passed in character, as it is in
the example. Code that prints out a solid square of that character is not acceptable.

3.6 We fixed justvowels so that it works with lowercase or uppercase vowels. Fix
notvowels so that it doesn’t print out uppercase vowels. (Try it as it is in the chapter, and
you will see that it does print uppercase vowels, even though the function is supposed to
only print not vowels.) Actually, do two versions of notvowels, using each of the two
methods that we used to fix justvowels.

1. Explicitly checking for uppercase vowels:

def notvowels(string):
for letter in string:
if not (letter in "aeiouAEIOU"):
print letter

2. Using the string method “lower()”:

def notvowels(string):
for letter in string:
if not letter.lower() in "aeiou":
print letter

Note: This version does not explicitly check for consonants, but just if a character is not a
vowel. One could instead remove the “not” and check against
“qwrtypsdfghjklzxcvbnmQWRTYPSDFGHJKLZXCVBNM” and
“qwrtypsdfghjklzxcvbnm” or some variation thereof.

3.7 One of the below programs that when called like this (with the underscore
representing a digit from 1 to 4) generates this output:

>>> dup_("rubber duck")


’kcud rebburrubber duck’

“dup3” generates the desired output. “dup1” just returns the passed in value. “dup2”
returns the passed in string repeated a number of times equal to the size of the passed in

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


string, beginning with a “_” character. “dup4” returns a reversed version of a passed in
string.

3.8 Try giving our doubledutch program a full name like “John Smith.” What happens to
the space?

The space is treated as a consonant, such that you get a response like:
JuJohuhnun u SuSmumituthuh

What if you include punctuation like periods or hyphens?

Anything that is not a vowel is treated as a consonant, therefore periods and hyphens are
also treated as consonants. Therefore you get responses like:
>>> doubledutch("Mr. John Brown-Smith")
MuMrur.u. u JuJohuhnun u BuBrurowuwnun-u-SuSmumituthuh

How could you create more full featured doubledutch that gets around these problems?
There are a couple of ways to get around these problems. One way is to simply check
first if there are any special characters in the string. Otherwise, one could explicitly list
all consonants, instead of simply checking if characters are not vowels.

3.9 Write a program that accepts a string as input, then prints out the vowels in that string
and then prints the consonants in that string.

This is simply a matter of combining justvowels and notvowels:

def splitem(name):
vowels= ""
consonants = ""
for letter in name:
if letter.lower() in "aeiou":
vowels = vowels + letter
if letter.lower() in "qwrtypsdfghjklzxcvbnm":
consonants = consonants + letter
print "Vowels: "+vowels
print "Consonsants: "+consonants

Note: This version explicitly checks for consonants, instead if a character is not a vowel.
A version in which that line is replaced with: if not letter.lower() in "aeiou": would also
be acceptable.

3.10 Change the encode function so that spaces are simply skipped.

def encode(string,keyletters):
alpha="abcdefghijklmnopqrstuvwxyz"
secret = ""
for letter in string:

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


if not letter.lower() in " ":
index = alpha.find(letter)
secret = secret+keyletters[index]
print secret

3.11 Change the encode function so that punctuation is simply skipped.

def encode(string,keyletters):
alpha="abcdefghijklmnopqrstuvwxyz"
secret = ""
for letter in string:
if not letter.lower() in ",.?:;-_'!":
index = alpha.find(letter)
secret = secret+keyletters[index]
print secret

Note: This code does not skip spaces, but one could add a space to the check against
string to accomplish that.

3.12 The buildCipher function could create more complicated alphabets. As long as both
the receiver and the sender generate the alphabet in the same way, the message needs to
only include the keyword for encoding and decoding to work. Try building these
variations:

Put the keyword at the end of the alphabet, rather than the front:

Note: This is accomplished simply by changing the final line.

def buildCipher(key):
alpha="abcdefghijklmnopqrstuvwxyz"
rest = ""
for letter in alpha:
if not( letter in key ):
rest = rest + letter
print rest+key

Reverse the alphabet before concatenating it to the keyword:

Note: This is accomplished by adding a reversal of the “rest” variable prior to


concatenating.

def buildCipher(key):
alpha="abcdefghijklmnopqrstuvwxyz"
rest = ""
for letter in alpha:
if not( letter in key ):
rest = rest + letter

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


restReverse = ""
for letter in rest:
restReverse = letter+restReverse

print key + restReverse

Separate the vowels and the consonants in the rest of the alphabet so that the cipher
alphabet is keyword, then the rest of the vowels, then the rest of the consonants:

Note: We can simply duplicate the work from 3.9 to achieve the desired effect.

def buildCipher(key):
alpha="abcdefghijklmnopqrstuvwxyz"
rest = ""
for letter in alpha:
if not( letter in key ):
rest = rest + letter

vowels= ""
consonants = ""
for letter in rest:
if letter.lower() in "aeiou":
vowels = vowels + letter
if letter.lower() in "qwrtypsdfghjklzxcvbnm":
consonants = consonants + letter

print key + vowels + consonants

3.13 One of the below programs that when called like this (with the underscore
representing a digit from 1 to 4) generates this output: 

>>> dup_("alphabet")

’_alphabetalphabetalphabetalphabetalphabetalphabetalphabetalphabet’

“dup2” is the correct program from below question 3.7 as it begins the returned string
with an underscore and repeats the passed in string a number of times equal to the string’s
length.

Note: Students may be confused by the wording “below programs”, as none of the
dupTimes programs output the correct value. dupTimes1 returns 'aallpphhaabbeett',
dupTimes2 returns 'lpphhhaaaabbbbbeeeeeettttttt', dupTimes3 returns '_alphabet', and
dupTimes4 does not compile.

3.14 One of the below programs that when called like this (with the underscore
representing a digit from 1 to 4) generates this output:

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


>>> findem_ (4)
’abcdabcdabcdabcdabcdabcda’

“findem4” returns the desired output, once the “\” symbol has been removed.

Note: The last three functions all have “\” symbols before the “%” symbol that causes
them not to compile. “findem4” returns the output due to the modulo operation leading to
asking for the same indexes several times over. This can be seen by stepping through the
for loop. On the 0th step, the function adds the 0th index of the letters string to the variable
piles. This continues with each step adding that index till the 4th step, where the modulo
operation again leads to the 0th index, then for the 5th step the 1st index and so on.

3.15 One of the below programs that when called like this (with the underscore
representing a digit from 1 to 4) generates this output:

>>> mixem_("we hold these truths")


’w.e. .h.o.l.d. .t.h.ese truths’

“mixem2” returns the desired output.

Note: “mixem2” simply adds periods after each character for the first half of the string,
then adds the second half of the passed in string.

3.16 You have written an essay for school, and it has to be at least five pages long. But
your essay is only 4.5 pages long! You decide to use your new Python skills to make your
essay longer by spacing out the letters. Write a function that takes a string and a number
of spaces to insert between each letter, then print out the resulting string.

def spaceitout(astring, number):


pile = ""
space = " "
for index in range(0,len(astring)-1):
pile = pile+ astring[index]+number*space
pile+=astring[len(astring)-1]

print pile

Note: The question specifically calls for spaces to be inserted between each letter.
Therefore, a solution such as:

def spaceitout(astring, number):


pile = ""
space = " "
for index in range(0,len(astring)):
pile = pile+ astring[index]+number*space

print pile

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Would be close, but actually have extra spaces after the final character as well.

3.17 Same problem as before, but you decide to use more of your new Python skills. You
are going to increase the spaces between the words. Write a function that takes a string
and a number of spaces to insert between each word, then print out the resulting string.

def spaceout(astring, number):


pile = ""
space = " "
parts = astring.split()
for index in range(0,len(parts)-1):
pile = pile+ parts[index]+number*space
pile = pile+parts[len(parts)-1]

print pile

Note: Information on the “split()” method can be found on Chapter 3, Page 63.
Additionally, the question specifically calls for spaces to be inserted between each word,
not after each, which requires an implementation similar to the above. A simpler function
that prints spaces after every word, even the last one, would be:

def spaceout(astring, number):


pile = ""
space = " "
parts = astring.split()
for index in range(0,len(parts)):
pile = pile+ parts[index]+number*space

print pile

Chapter 4
4.1

Why don’t we see red, green, and blue spots at each position in our picture?

Because each pixel is made up of a combination of red, green, and blue, not three
distinct spots of each. (Note: Chapter 4, Page 77)

What is hierarchical decomposition? What is it good for?

Hierarchical decomposition is a problem solving technique of breaking a complex


problem into simpler and simpler parts until you can solve each part. It’s good for
creating complex programs out of pieces that you understand. (Note: Chapter 4, Page
99)

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


What is luminance?

There are couple potential answers to this question based on the book:
-The human visual system for processing black and white (Source: Chapter 4, Page 76)
-The intensity of a color, that can be computed with the formula (red+green+blue)/3
(Source: Chapter 4, Page 104)

Why is the maximum value of any color component (red, green, or blue) 255?

Because eight bits can represent 256 unique combinations we have a maximum value
of 255, since one combination must account for 0. (Source: Chapter 4, Page 78)

The color encoding we’re using is RGB. What does this mean, in terms of the amount of
memory required to represent color? Is there a limit to the number of colors that we can
represent? Are there enough colors representable in RGB?

RGB means that every color is made up of a combination of three different primary
colors, each represented by eight bits each. This gives us a total of twenty-four bits of
color possibilities, for a total of 16,777,216 colors. Humans can see more than sixteen
million colors, but since no device exists that can express all the color variations we
can see, the RBG model is enough.
(Source: Chapter 4, Page 78)

4.2 Program 34 (page 89) obviously reduces the red by too much. Write a version that
only reduces the red by 10%, then one by 20%. Can you find pictures where each is most
useful? Note that you can always repeatedly reduce the red in a picture but you don’t
want to have to do it too many times.

10% version:

def decreaseRed(picture):
for pix in getPixels(picture):
value=getRed(pix)
setRed(pix,value*0.1)
20% version:

def decreaseRed(picture):
for pix in getPixels(picture):
value=getRed(pix)
setRed(pix,value*0.2)

4.3 Write the blue and green versions of the reduce red function—Program 9 (page 56).

Note: The program it refers to is actually the reduce red function, Program 34 (page 89).

def decreaseBlue(picture):

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


for pix in getPixels(picture):
value=getBlue(pix)
setBlue(pix,value*0.5)

def decreaseGreen(picture):
for pix in getPixels(picture):
value=getGreen(pix)
setGreen(pix,value*0.5)

4.4 Each of the following is equivalent to the increase red function—Program 35 (page
94). Test them and convince yourself that they work. Which do you prefer and why?

Note: This is an open-ended question as there are reasons to prefer both.

increaseRed2: This program is much slimmer, taking up only three lines. It also avoids
creating unnecessary variables.
increaseRed3: This program takes up much more space than “increaseRed2”, but its
much clearer exactly what’s happening.

4.5 If you keep increasing the red value and wrapping is on, eventually some pixels
become bright green and blue. If you check those pixels with the picture tool, you’ll find
that the values of red are very low. What do you think is going on? How did they get so
small? How does wrapping work?

What’s going on is that because a color can only be of values 0-255, so if wrapping is
turned on, any value above 255 just wraps to the modulo remainder. So if you’re upping
the red values by 10 each time, and you are already at 255, you’ll end up with
255+10=260%255 = 10. In that way you can go from a very large value to a very small
one while increasing.
(Source: Chapter 4, Page 94)

4.6 Write a function to swap the values of two colors, for example, swap the red value
with the blue value.

def swapRedBlue(picture):
for pix in getPixels(picture):
valueBlue=getBlue(pix)
valueRed=getRed(pix)
setRed(pix,valueBlue)
setBlue(pix,valueRed)

Note: You could pick any swap combination of the three colors (red, green, or blue). The
only change would be in which “get” and which “set” methods were used.

OR

def swapRedBlue(picture):
for pix in getPixels(picture):

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


valueBlue=getBlue(pix)
valueRed=getRed(pix)
valueGreen=getGreen(pix)
setColor(pix,makeColor(valueBlue,valueGreen,valueRed))

4.7 Write a function to set the red, green, and blue values to zero. What is the result?

def setAllZero(picture):
for pix in getPixels(picture):
setRed(pix,0)
setBlue(pix,0)
setGreen(pix,0)

OR

def setAllZero(picture):
for pix in getPixels(picture):
setColor(pix, makeColor(0,0,0))

The result is the entire image is set to black.

4.8 Write a function to set the red, green, and blue values to 255. What is the result?

def setAllMax(picture):
for pix in getPixels(picture):
setRed(pix,255)
setBlue(pix, 255)
setGreen(pix, 255)

OR

def setAllMax(picture):
for pix in getPixels(picture):
setColor(pix, makeColor(255, 255, 255))

The result is the entire image is set to white.

4.9 What does the following function do?

“test1” sets all the red values in the passed in picture to a third of their current value.

4.10 What does the following function do?

“test2” increases all of the blue values in the passed in picture by fifty percent.

4.11 What does the following function do?

“test3” sets all of the green values in the picture to zero.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


4.12 What does the following function do?

“test4” increases all the values of the pixels of the picture by ten.

4.13 What does the following function do?

“test5” decreases all of the values of the pixels of the picture by twenty.

4.14 What does the following function do?

“test6” swaps the values of the colors for each pixel in the game. It sets the blue values to
the red values, the red values to the green values, and the green values to the blue values.

4.15 What does the following function do?

“test7” halves all the color values for each pixel of the picture.

4.16 What does the following function do? By reading the program without running it, do
you think that the result of test8 will be lighter or darker than the result of test7?

“test8” sets all color values in the picture to a third of their current value, it will therefore
lead to a darker image than “test7” that only halves the values.

4.17 What does the following function do? By reading the program without running it, do
you think that the result of test9 will be lighter or darker than the result of test7?

“test9” doubles the current color values for each pixel of the picture, it will therefor lead
to a lighter image than “test7” that halves the values.

4.18 Write a function to “blue-ify” a face. Write a function that accepts a picture as input.
If any pixel has a blue value less than 150, then set that pixel’s color to white. Try it on a
picture of a face and see what you get.

def blueify(picture):
for pix in getPixels(picture):
value = getBlue(pix)
if value<150:
setColor(pix,white)

Note: If the picture is dark enough, checking for values less than 150 may lead to a
mostly white image.

4.19 Write a general “blue-ify” function. Write a function that accepts a picture as input,
then doubles the blue value of every pixel and cut the red and green values in half.

def blueify2(picture):
for pix in getPixels(picture):
valueB = getBlue(pix)*2

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


valueR = getRed(pix)/2
valueG = getGreen(pix)/2
setColor(pix,makeColor(valueR,valueG,valueB))

4.20 Write a general “red-ify” function. Write a function that accepts a picture as input,
then doubles the red value of every pixel and cut the blue and green values in half.

def redify(picture):
for pix in getPixels(picture):
valueB = getBlue(pix)/2
valueR = getRed(pix)*2
valueG = getGreen(pix)/2
setColor(pix,makeColor(valueR,valueG,valueB))

4.21 Write a function to change a picture to grayscale and then negate it.

Note: All one has to do is combine the grayscale and negate methods (Program 42 and
Program 41 respectively).

def grayscale(picture):
for p in getPixels(picture):
intensity = (getRed(p)+getGreen(p)+getBlue(p))/3
setColor(p,makeColor(intensity ,intensity ,intensity))
for px in getPixels(picture):
red=getRed(px)
green=getGreen(px)
blue=getBlue(px)
negColor=makeColor(255-red, 255-green, 255-blue)
setColor(px,negColor)

OR (more simply)

def grayscale(picture):
for p in getPixels(picture):
intensity = (getRed(p)+getGreen(p)+getBlue(p))/3
intensity = 255-intensity
setColor(p,makeColor(intensity ,intensity ,intensity))

4.22 Write a function to create a lightened grayscale image. First, lighten the image by
adding 75 to the red, green, and blue components of every pixel. Since higher numbers
are closer to white, this should make the pixel lighter. Now, grayscale the new image.

def grayscale2(picture):
for p in getPixels(picture):
valueR = getRed(p)+75
valueG = getGreen(p)+75
valueB = getBlue(p)+75

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


setColor(p,makeColor(valueR ,valueG ,valueB))
for p in getPixels(picture):
intensity = (getRed(p)+getGreen(p)+getBlue(p))/3
setColor(p,makeColor(intensity ,intensity ,intensity))

OR (more simply)

def grayscale2(picture):
for p in getPixels(picture):
valueR = getRed(p)+75
valueG = getGreen(p)+75
valueB = getBlue(p)+75
intensity = (valueR+valueG+valueB)/3
setColor(p,makeColor(intensity ,intensity ,intensity))

4.23 Write a function to create a lightened grayscale image, by use makeLighter. First,
lighten the image by using the makeLighter function on each color. Now, grayscale the
new image. Compare the result to the picture created by the previous problem. How does
makeLighter compare to adding 75 to each of the red, green, and blue components of
every pixel?

def grayscale3(picture):
for p in getPixels(picture):
color = getColor(p)
color = makeLighter(color)
setColor(p,color)
intensity = (getRed(p)+getGreen(p)+getBlue(p))/3
setColor(p,makeColor(intensity ,intensity ,intensity))

Adding 75 to each red, green, and blue component outputs a much brighter image than
using makeLighter, except when using an already very bright image with wrapping
turned off.
(Source: Chapter 4, Page 109)

4.24 Write three functions, one to clear blue (Program 36 (page 94)) and one to clear red,
and one to clear green. For each of these, which would be the most useful in actual
practice? How about combinations of them?

Note: You don’t need to write a clearBlue function, just copy the one on page 94.

def clearBlue(picture):
for p in getPixels(picture):
setBlue(p,0)

def clearRed(picture):
for p in getPixels(picture):
setRed(p,0)

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


def clearGreen(picture):
for p in getPixels(picture):
setGreen(p,0)

While all of them could potentially be useful as a means of making an image look
different for artistic purposes, clearing out the red (assuming little to no red elsewhere in
the image) could help to avoid red-eye problems with flash photography. A combination
could also work for artistic purposes, seeing as it would leave you with an image that had
only values of the same primary color.

Note: There may be multiple potential answers to the second part of this question.

4.25 Rewrite the clear blue program (Program 36 (page 94)) to maximize blue (i.e., set it
to 255) instead of clearing it. Is this useful? Would the red or green versions of the
maximize function be useful? Under what conditions?

def maximizeBlue(picture):
for p in getPixels(picture):
setBlue(p,255)

This could potentially be useful for artistic reasons, for example to make an image appear
to be taken under water. Red or green versions could also be useful for artistic purposes.

4.26 Write a function that takes a picture as input, and make the top half of the picture
black.

def setHalfBlank(picture):
pixels = getPixels(picture)
for index in range(0,len(pixels)/2):
pixel = pixels[index]
setColor(pixel ,black)

4.27 The function copyHalf copied the top half of the picture into the bottom half. Write
a new function copyUpHalf that copies the bottom half of the picture into the top.

def copyUpHalf(picture):
pixels = getPixels(picture)
for index in range(0,len(pixels)/2):
pixel1 = pixels[index + len(pixels)/2]
color1 = getColor(pixel1)
pixel2 = pixels[index]
setColor(pixel2 ,color1)

4.28 The function mirrorHalf mirrors the top half of the picture onto the bottom half.
Write a new function mirrorUpHalf that mirrors the top half of the picture into the top.

Note: The question should read “mirrors the bottom half of the picture into the top”

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


def mirrorHalf(picture):
pixels = getPixels(picture)
target = len(pixels) – 1
for index in range(0,len(pixels)/2):
pixel1 = pixels[target]
color1 = getColor(pixel1)
pixel2 = pixels[index]
setColor(pixel2 ,color1)
target = target - 1

Chapter 5
5.1 Write a function called changeColor that takes as input a picture and an amount to
increase or decrease a color by and a number 1 (for red), 2 (for green), or 3 (for blue).
The amount will be a number between −.99 and .99.

def changeColor(picture, amount, number):


for p in getPixels(picture):
if number==1:
value = getRed(p)
value = value +value*amount
setRed(p,value)
if number ==2:
value = getGreen(p)
value = value +value*amount
setGreen(p,value)
if number ==3:
value = getBlue(p)
value = value +value*amount
setBlue(p,value)

Note: Because of the requirements of the question, unlike in the previous chapter the
value variable can’t just be multiplied by the amount variable. If one did it that way,
they’d end up with a image with ninety percent of the red removed with the function all
“changeColor(pict,−.10,1)” and not the ten percent requested.

5.2 Imagine that you have a picture, and you are painting a copy of it. But you have only
eight colors. Write a function that inputs a picture, and makes these changes to each
pixel. For each of red, green, and blue, if the component is less than 100, make it zero.
Otherwise, make it 255.

def paintLimited(picture):
for p in getPixels(picture):
valueR = getRed(p)
if valueR<100:
setRed(p,0)

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.

You might also like