FUNDAMENTALS OF PYTHON, FIRST PROGRAM 3RD EDITION BY KENNETH A. LAMBART SOLUTIONS MANUAL

Page 1


Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction

Solution and Answer Guide For All Chapters LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 1, INTRODUCTION

TABLE OF CONTENTS Exercise Solutions ....................................................................................................................................... 1 Exercise 1.1 ............................................................................................................................................... 1 Exercise 1.2 ............................................................................................................................................... 2 Exercise 1.3 ............................................................................................................................................... 3 Review Questions Answers......................................................................................................................... 4 Programming Exercises Solutions ............................................................................................................. 8 Debugging Exercises Solutions .................................................................................................................. 8

EXERCISE SOLUTIONS EXERCISE 1.1 1.

List three common types of computing agents. Solution:

Human beings, desktop computers, cell phones 2.

Write an algorithm that describes the second part of the process of making change (counting out the coins and bills). Solution: There are various ways to do this, but here is one: Repeat Select the largest unit of money that is less than or equal to the remaining change Subtract this unit from the remaining change Until the remaining change is 0 The collection of units selected represent the change

3.

Write an algorithm that describes a common task, such as baking a cake.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

1


Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction

Solution: There are various ways to do this, but here is one: Preheat an oven to 375 degrees Add 1 cup of water and 1 egg to a mixing bowl Beat the liquid mixture in the bowl until the ingredients are blended Add the contents of a boxed cake mix to the mixing bowl Beat the mixture in the bowl until the ingredients are blended Pour the contents of the mixing bowl into a lightly greased cake pan Bake the cake in the oven for 45 minutes

4.

Describe an instruction that is not well defined and thus could not be included as a step in an algorithm. Give an example of such an instruction. Solution: Attempting to divide a number by 0

5.

In what sense is a laptop computer a general-purpose problem-solving machine? Solution: A laptop computer is a general-purpose problem-solving machine because it is programmable and can solve any problem for which there is an algorithm.

6.

List four devices that use computers and describe the information that they process. (Hint: Think of the inputs and outputs of the devices.) Solution: Digital camera—images, music player—sound, cell phone—text, ATM—numbers

EXERCISE 1.2 1.

List two examples of input devices and two examples of output devices. Solution: Input devices—keyboard and mouse, output devices—monitor and speakers

2.

What does the central processing unit (CPU) do? Solution: The CPU fetches, decodes, and executes instructions.

3.

How is information represented in hardware memory? Solution: Information is represented using binary notation, which in hardware is a pattern of voltage levels.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

2


Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction

4.

What is the difference between a terminal-based interface and a graphical user interface? Solution: A terminal-based interface supports only the input and output of text with a keyboard and monitor. A graphical user interface supports the output of images and the manipulation of them with a pointing device, the mouse.

5.

What role do translators play in the programming process? Solution: A translator converts a program written in a high-level language (human readable and writable) to an equivalent program in a low-level language (machine readable and executable).

EXERCISE 1.3 1.

Describe what happens when the programmer enters the string "Greetings!" in the Python shell. Solution: Python reads the string "Greetings!", evaluates it, and displays this string (including single quotes) in the shell.

2. Write a line of code that prompts the user for their name and saves the user’s input in a variable called name. Solution:

name = input("Enter your name: ")

3.

What is a Python script? Solution: A Python script is a complete Python program that can be run from a computer’s operating system.

4. Explain what goes on behind the scenes when your computer runs a Python program. Solution: If the program has not already been translated, Python’s compiler translates it to byte code. The Python virtual machine then executes this code.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

3


Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction

REVIEW QUESTIONS ANSWERS 1.

Which of the following is an example of an algorithm? a.

A dictionary

b.

A recipe

c.

A shopping list

d.

The spelling checker of a word processor

Answer: b Feedback: a. b. c. d.

2.

Incorrect. A dictionary is a data structure. Correct. A recipe is a set of instructions that describes a process that halts with a solution to a problem. Incorrect. A shopping list is a data structure. Incorrect. A word processor is a program that consists of instructions and data.

Which of the following contains information? a.

An audio CD

b.

A refrigerator

c.

An automobile

d.

A stereo speaker

Answer: a Feedback: a. b. c. d.

3.

Correct. The information on an audio CD represents sound. Incorrect. A refrigerator contains just food, if it’s not empty. Incorrect. An automobile contains a steering wheel, engine, exhaust pipe, and so on. Incorrect. A stereo speaker contains a magnetic coil, wires, and so on.

Which of the following is a general-purpose computing device? a.

A smartphone

b.

A portable music player

c.

A microwave oven

d.

A programmable thermostat

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

4


Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction

Answer: a Feedback: a. b. c. d. 4.

Correct. A smartphone is capable of running any program. Incorrect. A portable music player is dedicated to the specialized tasks of playing digital music. Incorrect. A microwave is dedicated to the task of heating food. Incorrect. A programmable thermostat is dedicated to the specialized tasks of climate control.

Which of the following is an input device? a.

Speaker

b.

Microphone

c.

Printer

d.

Display screen

Answer: b Feedback: a. b. c. d.

5.

Incorrect. A speaker is a device for the output of sound. Correct. A microphone is a device for the input of sound. Incorrect. A printer is a device for the output of words or graphics on paper. Incorrect. A display screen is a device for the output of images and text.

Which of the following are output devices? a.

A digital camera

b.

A keyboard

c.

A flatbed scanner

d.

A monitor

Answer: d Feedback: a.

Incorrect. A digital camera is a device for the input of images.

b.

Incorrect. A keyboard is a device for the input of characters and commands via keystrokes.

c.

Incorrect. A flatbed scanner is a device for the input of images from paper.

d.

Correct. A monitor is a device for the visual display or output of words and graphics.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

5


Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction

6.

What is the purpose of the CPU? a.

Store information

b.

Receive inputs from the human user

c.

Decode and execute instructions

d.

Send output to the human user

Answer: c Feedback:

7.

a.

Incorrect. The purpose of memory is to store information.

b.

Incorrect. The purpose of input devices, such as a keyboard, is to receive input from the human user.

c.

Correct. The CPU contains circuitry that decodes and executes instructions.

d.

Incorrect. The purpose of output devices, such as a monitor, is to send output to the human user.

Which of the following translates and executes instructions in a programming language? a.

A compiler

b.

A text editor

c.

A loader

d.

An interpreter

Answer: d Feedback: a.

Incorrect. A compiler translates instructions in a source program to instructions in byte code or machine code.

b.

Incorrect. A text editor allows a programmer to edit and save source code for a program.

c.

Incorrect. A loader transfers instructions and data from external memory to random access memory at program startup.

d.

Correct. An interpreter both translates (compiles) and executes (runs) instructions in a programming language.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

6


Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction

8.

Which of the following outputs data in a Python program? a.

The input function

b.

The assignment statement

c.

The print function

d.

The main function

Answer: c a.

Incorrect. The input statement receives data from a file or at the keyboard and makes these data available to a running program.

b.

Incorrect. The assignment statement binds a variable to a value.

c.

Correct. The print statement sends data from a running program to a an output device, such as a monitor or a speaker.

d.

9.

Incorrect. The main function organizes a program at the top level into a sequence of instructions.

What is IDLE used to do? a.

Edit Python programs

b.

Save Python programs to files

c.

Run Python programs

d.

All of the other answers

Answer: d Feedback: a.

Correct. IDLE can be used for all three tasks.

b.

Correct. IDLE can be used to compile and run programs, too.

c.

Correct. IDLE can be used to edit and run programs, too.

d.

Correct.t IDLE can be used to edit and compile programs, too.

10. What is the set of rules for forming sentences in a language called? a.

Semantics

b.

Pragmatics

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

7


Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction

c.

Syntax

d.

Logic

Answer: c Feedback: a. b. c. d.

Incorrect. Semantics is the set of rules for interpreting the meaning of sentences in a language. Incorrect. Pragmatics is the set rules that describe the types of uses to which sentences in a language can be put. Correct. Semantics is the set of rules for forming sentences in a language. Incorrect. Logic is the set of rules for determining valid or invalid arguments in a language.

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 1.

Write a Python program in a file named myinfo.py that prints (displays) your name, address, and telephone number. (LO: 1.1) Solution: See myinfo.py posted on the Instructor Companion Site.

2.

Open an IDLE window and enter the program from Figure 1-7 that computes the area of a rectangle. Save the program to a file named rectangle.py and load it into the shell by pressing the F5 key and correct any errors that occur. Test the program with different inputs by running it at least three times. (LO: 1.1) Solution: See rectangle.py posted on the Instructor Companion Site.

3.

Write a program in a file named triangle.py to compute the area of a triangle. Issue the appropriate prompts for the triangle’s base and height. Then, use the formula .5

* base * height to

compute the area. Test the program from an IDLE window. (LO: 1.1) Solution: See triangle.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

8


Solution and Answer Guide For All Chapters: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 1, Introduction

4.

Write and test a program in a file named circle.py that computes the area of a circle. This program should request a number representing a radius as input from the user. It should use the formula 3.14

*

radius ** 2 to compute the area and then output this result suitably labeled. (LO: 1.1) Solution: See circle.py posted on the Instructor Companion Site.

5.

A cuboid is a solid figure bounded by six rectangular faces. Its dimensions are its height, width, and depth. Write a Python program in a file named cuboid.py that computes and prints the volume of a cuboid, given its height, width, and depth as inputs. The volume is just the product of these three inputs. The output should be labeled as ―cubic units.‖ Solution: See cuboid.py posted on the Instructor Companion Site.

DEBUGGING EXERCISES SOLUTIONS 1.

Consider the following interaction at the Python shell:

>>> first = input("Enter the first integer: ") Enter the first number: 23 >>> second = input("Enter the second integer: ") Enter the second number: 44 >>> print("The sum is", first + second) The sum of the two integers is 2344 The expected output is 67, but the output of this computation is 2344. Explain what causes this error and describe how to correct it. Solution

The program prints the value 2344 when given the inputs 23 and 44. The output is the result of applying the + operator to the two the input strings ―23‖ and ―44‖ to produce the resulting string ―2344‖. To produce the arithmetic sum of the integers 23 and 44, one should convert the input strings ―23‖ and ―44‖ to integer values, using the type conversion function int. The revised statements

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

9


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions

first = int(input("Enter the first integer: ")) second = int(input("Enter the second integer: "))

accomplish this. Then the + operator will perform an arithmetic sum on the two integers, producing the expected integer value of 67.

Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 2, SOFTWARE DEVELOPMENT, DATA T YPES, AND EXPRESSIONS

TABLE OF CONTENTS Exercise Solutions ..................................................................................................................................... 10 Exercise 2.1 ............................................................................................................................................. 10 Exercise 2.2 ............................................................................................................................................. 11 Exercise 2.3 ............................................................................................................................................. 12 Exercise 2.4 ............................................................................................................................................. 13 Review Questions Answers....................................................................................................................... 14 Programming Exercises Solutions ........................................................................................................... 18 Debugging Exercise Solution.................................................................................................................... 20

EXERCISE SOLUTIONS EXERCISE 2.1 7.

List four phases of the software development process and explain what they accomplish.

Solution:

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

10


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions

Analysis describes what a system does in terms of its input, outputs, and functions from a user’s perspective. Design describes how a system accomplishes its tasks. Coding produces the software for the system. Testing examines whether or not the software does what it is supposed to do. 8.

Jack says that he will not bother with analysis and design but proceed directly to coding his programs. Why is that not a good idea? Solution: Analysis and design provide detailed blueprints for coding a system. Without these blueprints, it may be difficult to determine whether the system will do what it is supposed to do, and it may be difficult to minimize errors in the code and structure it in a way that eases maintenance.

EXERCISE 2.2 6.

Let the variable x be "dog" and the variable y be "cat". Write the values returned by the following operations: a. x + y b.

"the " + x + " chases the " + y

c.

x * 4.

Solution: a. "dogcat" b. "the dog chases the cat" c. "dogdogdogdog"

7.

Write a string that contains your name and address on separate lines using embedded newline characters. Then write the same string literal without the newline characters. Solution: "Ken Lambert\nComputer Science\nWashington and Lee" """Ken Lambert Computer Science Washington and Lee"""

8.

How does one include an apostrophe as a character within a string literal? Solution: An apostrophe can be included in a string that is enclosed within double quotes.

9.

What happens when the print function prints a string literal with embedded newline characters? Solution: When the Python interpreter encounters a newline character while printing a string, the cursor moves to the next line of output before the rest of the characters are displayed.

10. Which of the following are valid variable names?

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

11


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions

a. b. c. d. e.

length _width firstBase 2MoreToGo halt!

Solution: a, b, and c

EXERCISE 2.3 5.

Which data type would most appropriately be used to represent the following data values? a.

The number of months in a year

b.

The area of a circle

c.

The current minimum wage

d.

The approximate age of the universe (12,000,000,000 years)

e.

Your name

Solution: a.

int

b.

float

c.

float

d.

int

e.

string

6. Explain the differences between the data types int and float. Solution:

int is the type of integers or whole numbers, whereas float is the type of numbers that include a whole part (digits to the left of a decimal point) and a fractional part (digits to the right of the decimal point).

7.

Write the values of the following floating-point numbers in Python’s scientific notation: a.

355.76

b.

0.007832

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

12


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions

c.

4.3212

Solution: a. 3.5576e2 b. 7.832e-3 c. 4.3212e0

8. Consult Table 2-5 to write the ASCII values of the characters '$' and '&'. Solution: 36 and 38.

EXERCISE 2.4 1.

Let x = 8 and y = 2. Write the values of the following expressions: a.

x + y * 3

b.

(x + y) * 3

c.

x ** y

d.

x % y

e.

x / 12.0

f.

x // 6

Solution: a. 14 b. 30 c. 64 d. 0 e. 0.66666666666666663 f. 1

2. Let x = 4.66. Write the values of the following expressions: a. round(x) b. int(x) Solution: © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

13


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions

a. 5.0 b. 4

3. How does a Python programmer round a float value to the nearest int value? Solution: Pass the number to the round function.

4. How does a Python programmer concatenate a numeric value to a string value? Solution: Pass the number as an argument the str function and use the result returned with the string and the + operator.

5. Assume that the variable x has the value 55. Use an assignment statement to increment the value of x by 1. Solution:

x = x + 1

REVIEW QUESTIONS ANSWERS 11. What does a programmer do during the analysis phase of software development? a.

Codes the program in a particular programming language

b.

Writes the algorithms for solving a problem

c.

Decides what the program will do and determines its user interface

d.

Tests the program to verify its correctness

Answer: c Feedback: e. f. g. h.

Incorrect. Coding occurs after design. Inorrect. Algorithms are written during design. Correct. This is a set of instructions that describes a process that halts with a solution to a problem. Incorrect. Testing occurs after coding.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

14


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions

12. What must a programmer use to test a program? a.

All possible sets of legitimate inputs

b.

All possible sets of inputs

c.

A single set of legitimate inputs

d.

A reasonable set of legitimate inputs

Answer: d Feedback: e. f. g. h.

Incorrect. There may be an infinite number of sets of possible legitimate inputs. Incorrect. Some inputs may not be legitimate, and only legitimate ones are candidates for testing. incorrect. The program might fail on a legitimate input that is not tested. Correct. A reasonable set of legitimate inputs is finite and includes those likely to produce correct results.

13. What must you use to create a multiline string? e.

A single pair of double quotation marks

f.

A single pair of single quotation marks

g.

A single pair of three consecutive double quotation marks

h.

Embedded newline characters

Answer: c, d Feedback: e. f. g. h.

Inorrect. This creates a string, but no newlines are specified. Incorrect. This creates a string, but no newlines are specified. Correct. This will create a multiline string if the string’s text is on multiple lines in the source programs. Correct. An embedded newline character causes a newline to print on the monitor.

14. What is used to begin an end-of-line comment? a.

/ symbol

b.

# symbol

c.

% symbol

d.

* symbol

Answer: b

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

15


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions

Feedback: e. f. g. h.

Incorrect. The / symbol serves as an arithmetic division operator or as a line separator in source code. Correct. The # symbol begins an end-of-line comment. Incorrect. The % operator serves as the arithmetic remainder operator. Incorrect. The * symbol serves as the arithmetic multiplication operator.

15. Which of the following lists of operators is ordered by decreasing precedence? e.

+, *, **

f.

*, /, %

g.

**, *, +

h.

+, -

Answer: c Feedback: e.

Incorrect. These operators are ordered by increasing precedence.

f.

Incorrect. These operators have the same precedence.

g.

Correct. These operators are ordered by decreasing precedence.

h.

Incorrect. These operators have the same precedence.

16. The expression 2 ** 3 ** 2 evaluates to which of the following values? e.

64

f.

512

g.

8

h.

12

Answer: b Feedback: e.

Incorrect. This assumes that ** is left-associative.

f.

Correct. ** is right-associative, which means that 3 ** 2 is evaluated before the result, 9 is used as the exponent for 2 ** 9.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

16


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions

g.

Incorrect. This is the result of 2 * 3 + 2.

h.

Incorrect. This is the result of 2 * 3 * 2.

17. The expression round(23.67) evaluates to which of the following values? e.

23

f.

23.7

g.

24.0

h.

24

Answer: d Feedback: e.

Incorrect. This would be the result of using the int function, which truncates the argument.

f.

Incorrect. round with a single argument returns an int.

g.

Incorrect. round with a single argument returns an int.

h.

Correct. round rounds its single argument to the nearest whole number. In this case, it rounds up because the argument is greater than 23.5.

18. Assume that the variable name has the value 33. What is the value of name after the assignment name = name * 2 executes? e.

35

f.

33

g.

66

Answer: c e.

Incorrect. 35 is 33 + 2.

f.

Incorrect. A total distractor.

g.

Correct. 66 is double 33.

h.

Incorrect. 1089 is 33 ** 2.

19. Write an import statement that imports just the functions sqrt and log from the math module.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

17


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions

Answer:

from math import sqrt, log Feedback: Items can be imported from a module by listing them.

20. What are the purposes of the dir function and the help function? Answer: The dir function returns a list of the named resources (functions and variables) in its argument, which is a module. The help function displays all of the documentation for its argument, which can be a module or an item within a module.

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 6.

The tax calculator program of the case study outputs a floating-point number that might show more than two digits of precision. Use the round function to modify the program in the file taxform.py to display at most two digits of precision in the output number. (LO: 2.4) Solution: See taxform.py posted on the Instructor Companion Site.

7.

You can calculate the surface area of a cube if you know the length of an edge. Write a program in the file cube.py that takes the length of an edge (an integer) as input and prints the cube’s surface area as output. (LO: 2.4) Solution: See cube.py posted on the Instructor Companion Site.

8.

Five Star Retro Video rents VHS tapes and DVDs to the same connoisseurs who like to buy LP record albums. The store rents new videos for $3.00 a night and oldies for $2.00 a night. Write a program in the

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

18


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions

file fivestar.py that the clerks at Five Star Retro Video can use to calculate the total charge for a customer’s video rentals. The program should prompt the user for the number of each type of video and output the total cost. (LO: 2.3, 2.4) Solution: See fivestar.py posted on the Instructor Companion Site.

9.

Write a program in the file sphere.py that takes the radius of a sphere (a floating-point number) as input and then outputs the sphere’s diameter, circumference, surface area, and volume. (LO: 2.3, 2.4, 2.5) Solution: See sphere.py posted on the Instructor Companion Site.

10. An object’s momentum is its mass multiplied by its velocity. Write a program in the file momentum.py that accepts an object’s mass (in kilograms) and velocity (in meters per second) as inputs and then outputs its momentum. (LO: 2.3, 2.4) Solution: See momentum.py posted on the Instructor Companion Site.

11. The kinetic energy of a moving object is given by the formula KE = (1/ 2)mv2 where m is the object’s mass and v is its velocity. Modify the program you created in Programming Exercise 5 so that it prints the object’s kinetic energy as well as its momentum. (LO: 2.3, 2.4) Solution: See momentum.py posted on the Instructor Companion Site.

12. Write a program in the file minutes.py that takes as input a number of years and calculates and prints the number of minutes in that period of time. (LO: 2.4) Solution: See minutes.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

19


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 2, Software Development, Data Types, and Expressions

13. Light travels at 3 * 108 meters per second. A light-year is the distance a light beam travels in one year. Write a program in the file lightyear.py that expects a number of years as input and calculates and displays the value of the distance traveled in meters. (LO: 2.4) Solution: See lightyear.py posted on the Instructor Companion Site.

14. Write a program in the file klickstonauts.py that takes as input a number of kilometers and prints the corresponding number of nautical miles. Use the following approximations:

A kilometer represents 1/10,000 of the distance between the North Pole and the equator.

There are 90 degrees, containing 60 minutes of arc each, between the North Pole and the equator.

A nautical mile is 1 minute of an arc. (LO: 2.4)

Solution: See klickstonauts.py posted on the Instructor Companion Site.

10. An employee’s total weekly pay equals the hourly wage multiplied by the total number of regular hours plus any overtime pay. Overtime pay equals the total overtime hours multiplied by 1.5 times the hourly wage. Write a program in the file employeepay.py that takes as inputs the hourly wage, total regular hours, and total overtime hours and displays an employee’s total weekly pay. (LO: 2.3, 2.4) Solution: See employeepay.py posted on the Instructor Companion Site.

DEBUGGING EXERCISE SOLUTION Jill has written a program that computes the sales tax on the purchase of an item, given the price of the item (a floating-point number) and the percent tax rate (an integer). The output of the program is the purchase price, the tax, and the total amount to be paid. Here is her code:

purchasePrice = float(input("Enter the purchase price as $: ")) taxRate = int(input("Enter the tax rate as %: ")) tax = purchasePrice * taxRate

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

20


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

totalOwed = purchasePrice + tax print("Purchase price: ", purchasePrice) print("Tax:

", tax)

print("Total owed:

", totalOwed)

When she tested his program with a purchase price of $5.50 and a sales tax of 5%, Jill observed the following unexpected output: Enter the purchase price as $: 5.50 Enter the tax rate as %: 5 Purchase price:

5.5

Tax:

27.5

Total owed:

33.0

Describe the error, explain why it happened, and suggest a correction. Solution The code accepts an integer percent as input for the tax rate, but it does not divide this value by 100 to produce the correct floating-point form to use in the computation of the sales tax. To correct the problem, the program must reset taxRate to taxRate / 100 after the input.

Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 3, LOOPS AND SELECTION S TATEMENTS

TABLE OF CONTENTS Exercise Solutions ..................................................................................................................................... 22 Exercise 3.1 ............................................................................................................................................. 22 Exercise 3.2 ............................................................................................................................................. 23 Exercise 3.3 ............................................................................................................................................. 24 Exercise 3.4 ............................................................................................................................................. 26 Review Questions Answers....................................................................................................................... 27 Programming Exercises Solutions ........................................................................................................... 33 Debugging Exercise Solution.................................................................................................................... 37

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

21


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

EXERCISE SOLUTIONS EXERCISE 3.1 9.

Write the outputs of the following loops: a.

for count in range(5): print(count + 1, end = " ")

b.

for count in range(1, 4): print(count, end = " ")

c.

for count in range(1, 6, 2): print(count, end = " ")

d.

for count in range(6, 1, -1): print(count, end = " ")

Solution: a. b. c. d.

12345 123 135 65432

. 10. Write a loop that prints your name 100 times. Each output should begin on a new line. Solution:

for count in range(100): print("cat") 11. Explain the role of the variable in the header of a for loop. Solution: On each pass through the loop, the header’s variable is automatically assigned the next value in a sequence. The sequence of values is determined by the other information in the header. 12. Write a loop that prints the first 128 ASCII values followed by the corresponding characters (see the section on characters in Chapter 2). Be aware that most of the ASCII values in the range ―0..31‖ belong to special control characters with no standard print representation, so you might see strange symbols in the output for these values.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

22


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

Solution:

for ascii in range(128): print(ascii, chr(ascii)) 13. Assume that the variable testString refers to a string. Write a loop that prints each character in this string, followed by its ASCII value. Solution:

for ch in testString: print(ch, ord(ch))

EXERCISE 3.2 11. Assume that the variable amount refers to 24.325. Write the outputs of the following statements: a.

print("Your salary is $%0.2f" % amount)

b.

print("The area is %0.1f" % amount)

c.

print("%7f" % amount)

Solution: a. Your salary is $24.32 b. The area is 24.3 c. 24.325000

12. Write a code segment that displays the values of the integers x, y, and z on a single line, such that each value is right-justified with a field width of 6. Solution:

print("%6d%6d%6d" % (x, y, z)) 13. Write a format operation that builds a string for the float variable amount that has exactly two digits of precision and a field width of zero. Solution:

"%0.2f" % amount 14. Write a loop that outputs the numbers in a list named salaries. The outputs should be formatted in a column that is right-justified, with a field width of 12 and a precision of 2. Solution:

for number in salaries: print("%12.2f" % number)

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

23


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

EXERCISE 3.3 1.

Assume that x is 3 and y is 5. Write the values of the following expressions: a.

x == y

b.

x > y -3

c.

x <= y - 2

d.

x == y or x > 2

e.

x != 6 and y > 10

f.

x > 0 and x < 100

Solution: a. False b. True c. True d. True e. False f. True

2.

Assume that x refers to an integer. Write a code segment that prints the integer’s absolute value without using Python’s abs function. Solution:

if x < 0: print(-x) else: print(x) 3.

Write a loop that counts the number of space characters in a string. Recall that the space character is represented as ' '. Solution:

count = 0 for ch in theString: if ch == " ": count += 1 print(count) 4.

Assume that the variables x and y refer to strings. Write a code segment that prints these strings in alphabetical order. You should assume that they are not equal. Solution:

if x < y: print(x, y) © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

24


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

else: print(y, x) 5.

Explain how to check for an invalid input number and prevent it being used in a program. You may assume that the user enters a number. Solution: After the input is received, it is compared to the lower and upper bounds of the range of valid numbers. If the number is less than or equal to the upper bound and greater than or equal to the lower bound, it is used in the computation. Otherwise, the program moves to the next statement after the selection statement.

6.

Construct truth tables for the following Boolean expressions: a. not (A or B) b. not A and not B Solution: a.

A True True False False

B True False True False

not (A or B) False False False True

B True False True False

not A and not B False False False True

b.

A True True False False

7.

Explain the role of the trailing else part of an extended if statement. Solution: The trailing else part of an extended if statement includes the default action that is performed if none of the conditions that occur earlier in the statement are true.

8.

The variables x and y refer to numbers. Write a code segment that prompts the user for an arithmetic operator and prints the value obtained by applying that operator to x and y. Solution:

op = input("Enter an arithmetic operator: ") if op == "+": print(x + y) elif op == "-": print(x - y) elif op == "*": print(x * y) elif op == "/": print(x / y)

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

25


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

else: print(x % y) 9.

Does the Boolean expression count > 0 and total // count > 0 contain a potential error? If not, why not? Solution: No, the statement does not contain an error, which to a casual reader might look like an attempt to divide a number by zero. The first comparison detects when the number is zero, and then short-circuit evaluation of the and operation prevents the second comparison from being executed.

EXERCISE 3.4 1.

Translate the following for loops to equivalent while loops:

for count in range(100): print(count) b. for count in range(1, 101): print(count) c. for count in range(100, 0, -1): print(count) a.

Solution:

count = 0 while count < 100: print(count) count += 1 b. count = 1 while count <= 100: print(count) count += 1 c. count = 100 while count > 0: print(count) count -= 1 a.

6. The factorial of an integer N is the product of the integers between 1 and N, inclusive. Write a while loop that computes the factorial of a given integer N. Solution:

product = 1 count = 1 while count <= n: product *= count count += 1

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

26


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

7. The log2 of a given number N is given by M in the equation N = 2M. Using integer arithmetic, the value of M is approximately equal to the number of times N can be evenly divided by 2 until it becomes 0. Write a loop that computes this approximation of the log2 of a given number N. You can check your code by importing the math.log function and evaluating the expression round(math.log(N, 2)) (note that the math.log function returns a floating-point value). Solution:

logbase2 = 0 while n > 0: n //= 2 logbase2 += 1 logbase2 -= 1 8. Describe the purpose of the break statement and the type of problem for which it is well suited. Solution: The break statement exits the enclosing loop statement. The break statement can be used when a loop must execute at least one pass. In that case, a break statement is embedded in an if statement that tests for the truth of a termination condition for the loop. This if statement usually occurs in the middle or at the end of the loop’s body.

9. What is the maximum number of guesses necessary to guess correctly a given number between the numbers N and M? Solution: log2(M - N + 1)

10.

What happens when the programmer forgets to update the loop control variable in a while loop?

Solution: The loop might not halt.

REVIEW QUESTIONS ANSWERS 21. How many times does a loop with the header for count in range (10): execute the statements in its body? e.

9 times

f.

10 times

g.

11 times

h.

12 times

Answer: b

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

27


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

Feedback: i. j. k. l.

Incorrect. Off by 1 (too few). Correct. The single argument to range specifies the number of iterations. Incorrect. Off by 1 (too many). Incorrect. Off by 2 (too many).

22. A for loop is convenient for a.

making choices in a program.

b.

running a set of statements a predictable number of times.

c.

counting through a sequence of numbers.

d.

describing conditional iteration.

Answer: b, c Feedback: i. j. k. l.

Incorrect. The if/else statement is used to make choices. Correct. The for loop’s header can specify the number of iterations. Correct. The for loop’s header includes a variable that is bound to each integer in a range of integers, and this variable can be referenced in the body of the loop. incorrect. The while loop is used for conditional iteration.

23. What is the output of the loop for count in range(5): print(count, end = " ")? i.

12345

j.

1234

k.

01234

l.

012345

Answer: c Feedback: i. j. k. l.

Inorrect. When range has a single argument, its sequence of integers begins with 0, not 1. Incorrect. range counts through the number of integers specified by its single argument (5), and there are only 4 of these in this answer. Correct. range counts through the integers from 0 through its single argument minus 1 (4 in this case). Incorrect. range counts through the number of integers specified by its single argument (5), and there are 6 of these in this answer.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

28


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

24. When the function range receives two arguments, what does the second argument specify? a.

The last value of a sequence of integers

b.

The last value of a sequence of integers plus 1

c.

The last value of a sequence of integers minus 1

d.

The step value for the loop

Answer: b Feedback: i. j. k. l.

Incorrect. This would be off by 1 (too many). Correct. range with two arguments visits integers from the first argument through the last argument minus 1, so that argument equals this integer plus 1. Incorrect. This would be off by 1 (too few). Incorrect. range would need three arguments to specify a step value (the third argument).

25. Consider the following code segment:

x = 5 y = 4 if x > y: print(y) else: print(x) What value does this code segment print? a.

4

b.

5

c.

9

d.

20

Answer: a Feedback: i.

Correct. x (5) is greater than y (4), so y (4) is printed.

j.

Incorrect. x (5) is not less than or equal to y (4), so x (5) is not printed.

k.

Incorrect. x (5) is not the sum of 4 and 5.

l.

Incorrect. x (5) is not the product of 4 and 5.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

29


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

26. A Boolean expression using the and operator returns True when i.

both operands are true

j.

one operand is true

k.

neither operand is true

l.

one operand is false

Answer: a Feedback: i.

Correct. The and operator returns True only when both of its operands are true.

j.

Incorrect. The and operator returns False when only one of its operands is true.

k.

Incorrect. The and operator returns False when neither of its operands is true.

l.

Incorrect. The and operator returns False when one of its operands is false

27. By default, the while loop is a(n) i.

entry-controlled loop

j.

exit-controlled loop

k.

count-controlled loop

l.

loop that iterates a definite, preestablished number of times

Answer: a Feedback: i.

Correct. The while loop’s continuation condition is tested at the top of the loop. If this condition is false, the statements within the loop are not executed.

j.

Incorrect. When the final statement in the while loop’s body is executed, control is returned to the condition at the top of the loop.

k.

Incorrect. Sometimes, but not always.

l.

Incorrect. Sometimes, but not always.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

30


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

28. Consider the following code segment:

count = 5 while count > 1: print(count, end = " ") count -= 1

What is the output produced by this code? a.

12345

b.

2345

c.

54321

d.

5432

Answer: d Feedback: i.

Incorrect. The loop counts down, as shown by the use of the > operator in its continuation condition and the decrement of the loop control variable.

j.

Incorrect. The loop counts down, as shown by the use of the > operator in its continuation condition and the decrement of the loop control variable.

k.

Incorrect. The loop does not include 1 in the output, because the continuation condition is false when the loop control variable equals 1.

l.

Correct. The loop counts down from 5 to 2 and prints these values, but does not print 1, which halts the loop.

29. Consider the following code segment, which is intended to print the integers 1 through 10:

count = 1 while count <= 10: print(count, end = " ") Which of the following describes the error in this code? a.

The loop is off by 1

b.

The loop control variable is not properly initialized.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

31


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

c.

The comparison points the wrong way.

d.

The loop is infinite.

Answer: d Feedback: a.

Incorrect. It appears that the loop will visit all of the numbers from 1 to 10.

b.

Incorrect. The loop control variable is properly initialized for the sequence 1 through 10.

c.

Incorrect. It appears that the loop is set up to halt when count becomes 11.

d.

Correct. The loop does not update the loop control variable by incrementing it, so its value will always be 1, so it will never reach 11, so the continuation condition, count <= 10, will always be true.

30. Consider the following code segment:

theSum = 0.0 while True: number = input("Enter a number: ") if number == "": break theSum += float(number)

How many iterations does this loop perform? a.

None

b.

At least one

c.

Zero or more

d.

Ten

Answer: b Feedback: a.

Incorrect. The loop’s continuation condition, True, causes the loop to execute at least once.

b.

Correct. The loop executes until the user enters the empty string (presses just the return key) as input. Because the loop’s continuation condition is always true, at least one input must occur.

c.

Incorrect. Because the loop’s continuation condition is always true, at least one input must occur.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

32


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

d.

Incorrect. The loop might take10 inputs, but this might not always be the case. The loop takes one or more inputs until the user just presses the return key.

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 15. Write a program in the file equilateral.py that accepts the lengths of three sides of a triangle as inputs. The program output should indicate whether or not the triangle is an equilateral triangle. (LO: 3.3) Solution: See equilateral.py posted on the Instructor Companion Site.

16. Write a program in the file right.py that accepts the lengths of three sides of a triangle as inputs. The program output should indicate whether or not the triangle is a right triangle. Recall from the Pythagorean theorem that in a right triangle, the square of one side equals the sum of the squares of the other two sides. (LO: 3.3) Solution: See right.py posted on the Instructor Companion Site.

17. Modify the guessing-game program of Section 3.5 in the file guess.py so that the user thinks of a number that the computer must guess. The computer must make no more than the minimum number of guesses, and it must prevent the user from cheating by entering misleading hints. (Hint: Use the math.log function to compute the minimum number of guesses needed after the lower and upper bounds are entered.) (LO: 3.3, 3.4) Solution: See guess.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

33


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

18. A standard science experiment is to drop a ball and see how high it bounces. Once the ―bounciness‖ of the ball has been determined, the ratio gives a bounciness index. For example, if a ball dropped from a height of 10 feet bounces 6 feet high, the index is 0.6, and the total distance traveled by the ball is 16 feet after one bounce. If the ball were to continue bouncing, the distance after two bounces would be 10 ft + 6 ft + 6 ft + 3.6 ft = 25.6 ft. Note that the distance traveled for each successive bounce is the distance to the floor plus 0.6 of that distance as the ball comes back up. Write a program in the file bouncy.py that lets the user enter the initial height from which the ball is dropped and the number of times the ball is allowed to continue bouncing. Output should be the total distance traveled by the ball. (LO: 3.1) Solution: See bouncy.py posted on the Instructor Companion Site.

19. A local biologist needs a program to predict population growth. The inputs would be the initial number of organisms, the rate of growth (a real number greater than 0), the number of hours it takes to achieve this rate, and a number of hours during which the population grows. For example, one might start with a population of 500 organisms, a growth rate of 2, and a growth period to achieve this rate of 6 hours. Assuming that none of the organisms die, this would imply that this population would double in size every 6 hours. Thus, after allowing 6 hours for growth, we would have 1000 organisms, and after 12 hours, we would have 2000 organisms. Write a program in the file population.py that takes these inputs and displays a prediction of the total population. (LO: 3.1) Solution: See population.py posted on the Instructor Companion Site.

20. The German mathematician Gottfried Leibniz developed the following method to approximate the value of π: π/4 = 1 - 1/3 + 1/5 - 1/7 + . . . Write a program in the file leibniz.py that allows the user to specify the number of iterations used in this approximation and that displays the resulting value. (LO: 3.1) Solution: See leibniz.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

34


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

21. Teachers in most school districts are paid on a schedule that provides a salary based on their number of years of teaching experience. For example, a beginning teacher in the Lexington School District might be paid $30,000 the first year. For each year of experience after this first year, up to 10 years, the teacher receives a 2% increase over the preceding value. Write a program in the file salary.py that displays a salary schedule, in tabular format, for teachers in a school district. The inputs are the starting salary, the percentage increase, and the number of years in the schedule. Each row in the schedule should contain the year number and the salary for that year. (LO: 3.1, 3.2) Solution: See salay.py posted on the Instructor Companion Site.

22. The greatest common divisor of two positive integers, A and B, is the largest number that can be evenly divided into both of them. Euclid’s algorithm can be used to find the greatest common divisor (GCD) of two positive integers. You can use this algorithm in the following manner: a.

Compute the remainder of dividing the larger number by the smaller number.

b.

Replace the larger number with the smaller number and the smaller number with the remainder.

c.

Repeat this process until the smaller number is zero.

d.

The larger number at this point is the GCD of A and B. Write a program in the file gcd.py that lets the user enter two integers and then prints each step in the process of using the Euclidean algorithm to find their GCD. (LO: 3.4)

Solution: See gcd.py posted on the Instructor Companion Site.

23. Write a program in the file sum.py that receives a series of numbers from the user and allows the user to press the enter key to indicate that he or she is finished providing inputs. After the user presses the enter key, the program should print the sum of the numbers and their average. (LO: 3.3, 3.4) Solution: See sum.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

35


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 3, Loops and Selection Statements

11. The credit plan at TidBit Computer Store specifies a 10% down payment and an annual interest rate of 12%. Monthly payments are 5% of the listed purchase price, minus the down payment. Write a program in the file tidbit.py that takes the purchase price as input. The program should display a table, with appropriate headers, of a payment schedule for the lifetime of the loan. Each row of the table should contain the following items: 

the month number (beginning with 1)

the current total balance owed

the interest owed for that month

the amount of principal owed for that month

the payment for that month

the balance remaining after payment

The amount of interest for a month is equal to balance * rate / 12. The amount of principal for a month is equal to the monthly payment minus the interest owed. (LO: 3.2, 3.3, 3.4) Solution: See tidbit.py posted on the Instructor Companion Site.

12. In the game of Lucky Sevens, the player rolls a pair of dice. If the dots add up to 7, the player wins $4; otherwise, the player loses $1. Suppose that, to entice the gullible, a casino tells players that there are lots of ways to win: (1, 6), (2, 5), and so on. A little mathematical analysis reveals that there are not enough ways to win to make the game worthwhile; however, because many people’s eyes glaze over at the first mention of mathematics, your challenge is to write a program in the file sevens.py that demonstrates the futility of playing the game. Your program should take as input the amount of money that the player wants to put into the pot, and play the game until the pot is empty. At that point, the program should print the number of rolls it took to break the player, as well as maximum amount of money in the pot. (LO: 3.3, 3.4) Solution: See sevens.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

36


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

DEBUGGING EXERCISE SOLUTION Jack has written a program that computes and prints the average of 10 test scores. The program prompts the user for each input score. Here is the code for this program:

count = 1 while count < 10: score = int(input("Enter test score number " + str(count) + ": ") total = total + score count = count + 1 average = total / count print("The average test score is", average) This program contains an error. State what type of error this is, describe how it is detected, and explain how to correct it. Solution When the program is run, the user is prompted for 9 inputs instead of the expected 10. This is a logic error. It is also a classic case of an off-by-one error, where the input loop performs one less iteration than expected. The cause of this is that the programmer has used the < operator instead of the <= operator to express the loop continuation condition. To guarantee that the loop iterates from 1 through 10, the programmer should replace the < operator with the <= operator in the loop header.

Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 4, STRINGS AND T EXT FILES

TABLE OF CONTENTS Exercise Solutions ..................................................................................................................................... 38 Exercise 4.1 ............................................................................................................................................. 38 Exercise 4.2 ............................................................................................................................................. 39 Exercise 4.3 ............................................................................................................................................. 39 Exercise 4.4 ............................................................................................................................................. 40 Review Questions Answers....................................................................................................................... 43 Programming Exercises Solutions ........................................................................................................... 47

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

37


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

Debugging Exercise Solution.................................................................................................................... 50

EXERCISE SOLUTIONS EXERCISE 4.1 14. Assume that the variable data refers to the string "myprogram.exe". Write the values of the following expressions: a.

data[2]

b.

data[-1]

c.

len(data)

d.

data[0:8]

Solution: a. b. c.

'p' 'e' 13 d. 'myprogra' 15. Assume that the variable data refers to the string "myprogram.exe". Write the expressions that perform the following tasks: a.

Extract the substring "gram" from data.

b.

Remove the extension ".exe" from data.

c.

Extract the character at the middle position from data.

Solution: a. b. c.

data[5:9] data[0:9] data[int(len(data) / 2)]

16. Assume that the variable myString refers to a string. Write a code segment that uses a loop to print the characters of the string in reverse order. Solution:

for index in range(len(myString) - 1, -1, -1): print(myString[index], end = '')

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

38


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

17. Assume that the variable myString refers to a string and the variable reversedString refers to an empty string. Write a loop that adds the characters from myString to reversedString in reverse order. Solution:

for ch in myString: reversedString = ch + reversedString

EXERCISE 4.2 15. Write the encrypted text of each of the following words using a Caesar cipher with a distance value of

+3: a.

Python

b.

hacker

c.

wow

Solution: a. sbwkrq b. kdfnhu c. zrz

16. Consult the Table of ASCII values in Chapter 2 and suggest how you would modify the encryption and decryption scripts in this section to work with strings containing all of the printable characters. Solution: The ASCII value for the letter ―z‖ would be replaced by the ASCII value 127 (the last character in the set), and the ASCII value for the letter ―a‖ would be replaced by the ASCII value 0 (the first character in the set).

17. You are given a string that was encoded by a Caesar cipher with an unknown distance value. The text can contain any of the printable ASCII characters. Suggest an algorithm for cracking this code. Solution: The decryption algorithm would be run with the encrypted text and each possible distance value (ranging from –127 through 127, excluding 0), and the results inspected for the plain text. The distance value that gives the plain text is then used to decrypt other encoded messages.

EXERCISE 4.3 9.

Translate each of the following numbers to decimal numbers: a.

110012

b.

1000002

c.

111112

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

39


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

Solution: f.

25

g.

32

h.

31

10.

Translate each of the following numbers to binary numbers:

a.

47110

b.

12710

c.

6410

Solution: a.

101111

b.

1111111

c.

1000000

11.

Translate each of the following numbers to binary numbers:

a.

4718

b.

1278

c.

648

Solution: a.

100111

b.

1010111

c.

110100

12.

Translate each of the following numbers to decimal numbers:

a.

4718

b.

1278

c.

648

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

40


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

Solution: a.

39

b.

87

c.

52

13.

Translate each of the following numbers to decimal numbers:

a.

4716

b.

2716

c.

AA16

Solution: a.

71

b.

295

c.

170

EXERCISE 4.4 2.

Assume that the variable data refers to the string "Python rules!". Use a string method from Table 4-2 to perform the following tasks: a.

Obtain a list of the words in the string.

b.

Convert the string to uppercase.

c.

Locate the position of the string "rules".

d.

Replace the exclamation point with a question mark.

Solution: d. e. f. g.

11.

data.split() data.upper() data.index("rules") data.replace("!", "?") Using the value of data from Exercise 1, write the values of the following expressions:

c. data.endswith('i')

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

41


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

d. "totally ".join(data.split(x)) Solution: c. False d. "Python totally rules! "

EXERCISE 4.5 1.

Write a code segment that opens a file named myfile.txt for input and prints the number of lines in the file. Solution:

count = 0 inputFile = open("myfile.txt", 'r') for line in inputFile: count += 1 print("There are", count, "lines.")

2.

Write a code segment that opens a file for input and prints the number of four-letter words in the file. Solution:

count = 0 inputFile = open("myfile.txt", 'r') for line in inputFile: wordlist = line.split() for word in wordlist: if len(word) == 4: count += 1 print("There are", count, "lines.") 3.

Assume that a file contains integers separated by newlines. Write a code segment that opens the file and prints the average value of the integers. Solution:

count = 0 sum = 0 inputFile = open("myfile.txt", 'r') for line in inputFile: sum += int(line.strip()) count += 1 if count == 0: average = 0 else:

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

42


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

average = sum / count print("The average is", average) 4.

Write a code segment that prints the names of all of the items in the current working directory. Solution:

from os import getcwd, listdir dirList = listdir(getcwd()) for name in dirList: print(name) 5.

Write a code segment that prompts the user for a filename. If the file exists, the program should print its contents on the terminal. Otherwise, it should print an error message. Solution:

from os.path import exists fileName = input("Enter a file name: ") if not exists(fileName): print("Error: the file does not exist!") else: inputFile = open(fileName, 'r') print(inputFile.read())

REVIEW QUESTIONS ANSWERS For questions 1–6, assume that the variable data refers to the string "No way!". 31. The expression len(data) evaluates to i.

8

j.

7

k.

6

Answer: b Feedback: m. n. o. p.

Incorrect. One character too many. Correct. There are seven characters in the string. Incorrect. One character too few. Incorrect. Three characters too many.

32. The expression data[1] evaluates to

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

43


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

a.

'N'

b.

'o'

c.

'p'

d.

'e'

Answer: b Feedback: m. n. o. p.

Incorrect. 'N' is at position 0 in the string. Correct. Position 1 is the second position in a string. 'p' is not in the string. 'e' is not in the string.

33. The expression data[-1] evaluates to m. '!' n.

'y'

o.

'o'

p.

'u'

Answer: a Feedback: m. n. o. p.

Correct. Position –1 accesses the last position in the string. Incorrect. Position –2 would access 'y' in the string. Incorrect. Position –5 would access 'o' in the string. Incorrect. 'u' is not in the string.

34. The expression data[3:6] evaluates to e.

'way!'

f.

'way'

g.

'wa'

h. 'w' Answer: b

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

44


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

Feedback: m. Incorrect. 3:6 accesses three characters, at positions 3 through 5 in the string. This answer shows characters at positions 3 through 6. n. Correct. 3:6 accesses three characters, at positions 3 through 5 in the string. o. Incorrect. 3:6 accesses three characters, at positions 3 through 5 in the string. This answer shows characters at positions 3 through 4. p. Incorrect. 3:6 accesses three characters, at positions 3 through 5 in the string. This answer shows characters at positions 3 through 4. 35. The expression data.replace("No", a.

'No way!'

b.

'Yo way!'

c.

'Yes way!'

d.

'My way!'

"Yes") evaluates to

Answer: c Feedback: m. Incorrect. This answer shows no replacement, where one is warranted. n.

Incorrect. This answer inserts the string 'Yo' instead of 'Yes'.

o.

Correct. This answer shows the replacement of 'No' with 'Yes'.

p.

Incorrect. This answer inserts the string 'Yo' instead of 'My'.

36. The expression data.find("way!") evaluates to m. 2 n.

3

o.

True

p.

False

Answer: b Feedback: m. Incorrect. This position is one to the left of the position of "way!" in the string. n.

Correct. This is the position of the first character of "way!" in the string.

o.

Incorrect. This method returns an integer position, not a Boolean value.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

45


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

p.

Incorrect. This method returns an integer position, not a Boolean value.

37. A Caesar cipher locates the coded text of a plaintext character m. a given distance to the left or to the right in the sequence of characters n.

in an inversion matrix

o.

by converting it to its ASCII integer value

p.

by replacing it with its binary representation

Answer: a Feedback: m. Correct. The Caesar cipher is a linear chipher, meaning that a coded character is located a given distance before or after the plaintext character, according to their values in the ASCII sequence. n.

Incorrect. An inversion matrix is used by a block cipher.

o.

Incorrect. The coded character is not an integer (ASCII value).

p.

Incorrect. The coded character is a character, not a binary number.

38. The binary number 111 represents the decimal integer h.

111

i.

3

j.

7

k.

8

Answer: c m. Incorrect. The only two values that are the same in binary and decimal are 0 and 1. n.

Incorrect. The decimal 3 is the same as the binary 11.

o.

Correct. If a binary number contains only 1s, you add 1 to get the next power of 2 in binary and convert that to decimal, and then subtract 1. In this case, the next power of 2 in binary is 111 + 1 = 1000. The exponent of this power of 2 is the number of 0s following the 1, so the decimal number is 23, or 8, and 8 – 1 = 7.

p.

Incorrect. The decimal 8 is the same as the binary 1000.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

46


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

39. Which of the following binary numbers represents the decimal integer value 8? a.

11111111

b.

100

c.

1000

d.

10000

Answer: c a.

Incorrect. A binary number consisting only of 1s is one less than a power of 2 in decimal.

b.

Incorrect. 100 is a power of 2 in decimal, but is 22 or 4.

c.

Correct. 1000 is a power of 2 in decimal, and 3 0s indicates that 3 is the exponent. So, this number is 23 in decimal, or 8.

d.

1000 is a power of 2 in decimal, but is 24 or 16.

40. Which file method is used to read the entire contents of a file in a single operation? a.

readline

b.

read

c.

a for loop

d.

input

Answer: b a.

Incorrect. This method reads a single line of text from a file.

b.

Correct. This method reads the entire text from a file and returns a string.

c.

Incorrect. This loop reads the text line by line from a file, binding each line to the loop control variable as it goes.

d.

Incorrect. This is the function for keyboard input.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

47


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on Cengage Instructor Center. 24. Write a script in the file encrypt.py that inputs a line of plaintext and a distance value and outputs an encrypted text using a Caesar cipher. The script should work for any printable characters. (LO: 4.1, 4.2) Solution: See encrypt.py posted on the Instructor Companion Site.

25. Write a script in the file decrypt.py that inputs a line of encrypted text and a distance value and outputs plaintext using a Caesar cipher. The script should work for any printable characters. (LO: 4.1, 4.2) Solution: See decrypt.py posted on the Instructor Companion Site.

26. Modify the scripts of Programming Exercises 1 and 2 to encrypt and decrypt entire files of text. (LO: 4.1, 4.5) Solution: See encrypt.py and decrypt.py posted on the Instructor Companion Site.

27. Octal numbers have a base of eight and the digits 0–7. Write the scripts octalToDecimal.py and decimalToOctal.py, which convert numbers between the octal and decimal representations of integers. These scripts use algorithms that are similar to those of the binaryToDecimal and

decimalToBinary scripts developed in Section 4-3. (LO: 4.1, 4.3) Solution: See octaltodecimal.py and decimaltooctal.py posted on the Instructor Companion Site.

28. A bit shift is a procedure whereby the bits in a bit string are moved to the left or to the right. For example, we can shift the bits in the string 1011 two places to the left to produce the string 1110. Note that the leftmost two bits are wrapped around to the right side of the string in this operation. Define two scripts, shiftLeft.py and shiftRight.py, that expect a bit string as an input. The script shiftLeft

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

48


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 4, Strings and Text Files

shifts the bits in its input one place to the left, wrapping the leftmost bit to the rightmost position. The script

shiftRight performs the inverse operation. Each script prints the resulting string. (LO: 4.1, 4.4) Solution: See shiftleft.py and shiftright.py posted on the Instructor Companion Site.

29. Use the strategy of the decimal to binary conversion and the bit shift left operation defined in

Programming Exercise 5 to code a new encryption algorithm in the file encrypt.py. The algorithm should add 1 to each character’s numeric ASCII value, convert it to a bit string, and shift the bits of this string one place to the left. A single-space character in the encrypted string separates the resulting bit strings. (LO: 4.1, 4.2, 4.4) Solution: See encrypt.py posted on the Instructor Companion Site.

30. Write a script in the file decrypt.py that decrypts a message coded by the method used in Programming Exercise 6. (LO: 4.1, 4.4) Solution: See decrypt.py posted on the Instructor Companion Site.

31. Write a script named copyfile.py. This script should prompt the user for the names of two text files. The contents of the first file should be input and written to the second file. (LO: 4.5) Solution: See copyfile.py posted on the Instructor Companion Site.

32. Write a script named numberlines.py. This script creates a program listing from a source program. This script should prompt the user for the names of two files. The input filename could be the name of the script itself, but be careful to use a different output filename! The script copies the lines of text from the input file to the output file, numbering each line as it goes. The line numbers should be right-justified in four columns, so that the format of a line in the output file looks like this example: (LO: 4.5)

1> This is the first line of text. Solution: See numberlines.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

49


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

13. Write a script named dif.py. This script should prompt the user for the names of two text files and compare the contents of the two files to see if they are the same. If they are, the script should simply output

"Yes". If they are not, the script should output "No", followed by the first lines of each file that differ from each other. The input loop should read and compare lines from each file. The loop should break as soon as a pair of different lines is found. (LO: 4.1, 4.5) Solution: See dif.py posted on the Instructor Companion Site.

DEBUGGING EXERCISE SOLUTION Jack just completed the program for the Flesch text analysis from this chapter’s case study. His supervisor, Jill, has discovered an error in his code. The error causes the program to count a syllable containing consecutive vowels as multiple syllables. Suggest a solution to this problem in Jack’s code and modify the program so that it handles these cases correctly. Solution To track whether a vowel has been seen multiple times within a word, introduce a Boolean variable within the outer loop, initially set to False. Then, in the first nested loop, if this variable is still False and the current character is a vowel, set this variable to True and increment the count of syllables; otherwise, if the character is not a vowel, reset this variable to False. The code for the modified program is included in the solutions to programming exercises.

Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 5, LISTS AND DICTIONARIES

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

50


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

TABLE OF CONTENTS Exercise Solutions ..................................................................................................................................... 51 Exercise 5.1 ............................................................................................................................................. 51 Exercise 5.2 ............................................................................................................................................. 53 Exercise 5.3 ............................................................................................................................................. 54 Exercise 5.4 ............................................................................................. Error! Bookmark not defined. Review Questions Answers....................................................................................................................... 55 Programming Exercises Solutions ........................................................................................................... 59 Debugging Exercise Solution.................................................................................................................... 62

EXERCISE SOLUTIONS EXERCISE 5.1 18. Assume that the variable data refers to the list [5, 3, 7]. Write the values of the following expressions: a.

data[2]

b.

data[-1]

c.

len(data)

d.

data[0:2]

e.

0 in data

f.

data + [2, 10, 5]

g.

tuple(data)

Solution: a. b. c. d. e. f. g.

7 7 3

[5, 3] False [5, 3, 7, 2, 10, 5] (5, 3, 7)

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

51


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

19. Assume that the variable data refers to the list [5, 3, 7]. Write the expressions that perform the following tasks: a.

Replace the value at position 0 in data with that value’s negation.

b.

Add the value 10 to the end of data.

c.

Insert the value 22 at position 2 in data.

d.

Remove the value at position 1 in data.

e.

Add the values in the list newData to the end of data.

f.

Locate the index of the value 7 in data, safely.

g.

Sort the values in data.

Solution: a. data[0] = -data[0] b. data.append(10) c. data.insert(2, 22) d. data.pop(1) e. data.extend(newData) f. if 7 in data:

position = data.index(7) else: position = -1 g. data.sort() 3.

What is a mutator method? Explain why mutator methods usually return the value None. Solution: A mutator method modifies the internal state of an object. A mutator method returns the value None because its purpose is just to modify the state of an object.

4.

Write a loop that accumulates the sum of the numbers in a list named data. Solution:

sum = 0 for item in data: sum += data 5.

Assume that data refers to a list of numbers, and result refers to an empty list. Write a loop that adds the nonzero values in data to the result list, keeping them in their relative positions.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

52


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

Solution:

for item in data: if item != 0: result.append(item) 6.

Write a loop that replaces each number in a list named data with its absolute value. Solution:

for index in range(len(data)): data[index] = abs(data[index]) 7.

Describe the costs and benefits of aliasing, and explain how it can be avoided. Solution: Aliasing occurs when two or more variables reference the same object. When this object is a large data structure, such as a list or dictionary, changes to the structure through one variable reference will have an impact on the other references. These side effects might not be anticipated by programmers who are using the other references. To protect against a side effect, each variable should refer to a copy of the object that has the same internal structure. The cost of this maneuver is the extra memory needed for the copies of the object.

8.

Explain the difference between structural equivalence and object identity. Solution:

Two objects are structurally equivalent if they are distinct objects and their contents are equal. Object identity involves just one object and possibly several references to it.

EXERCISE 5.2 18. What roles do the parameters and the return statement play in a function definition? Solution: A parameter requires the function’s caller to pass data to the function for its use when it is called. The return statement allows the caller to receive a value computed by the function. Both are mechanisms for sharing information between a function and its caller. 19. Define a function named even. This function expects a number as an argument and returns True if the number is divisible by 2, or it returns False otherwise. (Hint: A number is evenly divisible by 2 if the remainder is 0.) Solution:

def even(x): return x % 2 == 0

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

53


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

20. Use the function even to simplify the definition of the function odd presented in this section. Solution:

def odd(x): return not even(x) 21. Define a function named summation. This function expects two numbers, named low and high, as arguments. The function computes and returns the sum of the numbers between low and high, inclusive. Solution:

def summation(low, high): result = 0 for number in range(low, high + 1): result += number return result 22. What is the purpose of a main function? Solution: A main function provides an entry point for a program and structures its top-level tasks. .EXERCISE 5.3 14. Give three examples of real-world objects that behave like a dictionary.

Solution: Three examples of dictionary-like objects are encyclopedias, dictionaries, and cookbooks.

15.

Assume that the variable data refers to the dictionary {'b':20, 'a':35}. Write the values of the following expressions: a.

data['a']

b.

data.get('c', None)

c.

len(data)

d.

data.keys()

e.

data.values()

f.

data.pop('b')

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

54


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

data # After the pop above

g.

Solution: a. 35 b. None c. 2 d. ['b', 'a'] e. [20, 35] f. 20 g. {'a':35}

16. Assume that the variable data refers to the dictionary {'b':20, 'a':35}. Write the expressions that perform the following tasks: a.

Replace the value at the key 'b' in data with that value’s negation.

b.

Add the key/value pair 'c':40 to data.

c.

Remove the value at key 'b' in data, safely.

d.

Print the keys in data in alphabetical order.

Solution: a. data["b"] = -data["b"] b. data["c"] = 40 c. data.pop("b", None) d. keys = list(data.keys())

keys.sort() for key in keys: print(key)

REVIEW QUESTIONS ANSWERS For questions 1–6, assume that the variable data refers to the list [10, 20, 30]. 41. The expression data[1] evaluates to l.

10

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

55


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

m. 20 n.

30

o.

0

Answer: b Feedback: q. r. s. t.

Incorrect. 10 is at position 0. Correct. 1 is the second position in a list. Incorrect. 30 is at position 2. Incorrect. 0 is not in the list.

42. The expression data[1:3] evaluates to a.

[10, 20, 30]

b.

[20, 30]

c.

[10, 30]

d.

[30]

Answer: b Feedback: q. r. s. t.

Incorrect. 10 is at position 0, which does not begin the range 1:3. Correct. The range 1:3 includes data at positions 1 and 2. Incorrect. 10 and 30 are not in consecutive positions. Incorrect. The given slice includes two positions.

43. The expression data.index(20) evaluates to q.

1

r.

2

s.

True

t.

False

Answer: 1 Feedback: q. r.

Correct. 20 is at position 1 in the list. Incorrect. Position 2 is the third position in the list.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

56


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

s. t.

Incorrect. The index method returns an integer position. Incorrect. The index method returns an integer position.

44. The expression data + [40, 50] evaluates to i.

[10, 60, 80]

j.

[10, 20, 30, 40, 50]

k.

[50, 70]

l.

[0]

Answer: b Feedback: q. r. s. t.

Incorrect. 60 and 80 are not even in the two lists. Correct. A new list is built from the lists [10, 20, 30] and [40, 50]. Incorrect. 70 is not in either list. Incorrect. 0 is not in either list.

45. After the statement data[1] = 5, data evaluates to i.

[5, 20, 30]

j.

[10, 5, 30]

k.

5

l.

[10, 20, 5]

Answer: b Feedback: q.

Incorrect. The first position in a list is 0, not 1, so 5 should be in the second position.

r.

Correct. 20 is replaced with 5 at position 1, the second position.

s.

Incorrect. 5 is not a list.

t.

Incorrect. 30 was in position 2.

46. After the statement data.insert(1, 15), the original data is q.

[15, 10, 20, 30]

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

57


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

r.

[10, 15, 30]

s.

[10, 15, 20, 30]

t.

[10, 20, 30, 15]

Answer: c Feedback: q.

Incorrect. The first position in a list is 0, not 1, so 15 should be in the second position.

r.

Incorrect. The insert method does not replace the item at position 1, but shifts the items from positions 1 through the end of the list to the right by one, to open a hole for inserting the new item.

s.

Correct. 20 and 30 are shifted one position to the right, and 15 is inserted into position 1.

t.

Incorrect. 15 should be in the second position.

For questions 7–9, assume that the variable info refers to the dictionary {"name":"Sandy", "age":17}. 47. The expression list(info.keys()) evaluates to q.

("name", "age")

r.

["name", "age"]

s.

("Sandy", 17)

t.

(17, "Sandy")

Answer: b Feedback: q.

Incorrect. This answer is a tuple, but the list function returns a list.

r.

Correct. The keys method returns an iterator of a dictionary’s keys, which when fed to the list method returns a list.

s.

Incorrect. These are the dictionary’s values.

t.

Incorrect. These are the dictionary’s values.

48. The expression info.get("hobbies", None) evaluates to l.

"knitting"

m. None

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

58


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

n.

1000

o.

2000

Answer: b q.

Incorrect. There is no key/value pair for "hobbies" and "knitting".

r.

Correct. None is the default value returned for the absent key "hobbies".

s.

Incorrect. 1000 is not the default for get.

t.

Incorrect. 2000 is not the default for get.

49. The method to remove an entry from a dictionary is named a.

delete

b.

pop

c.

remove

d.

insert

Answer: b Feedback: a.

Incorrect. There is no delete method for dictionaries.

b.

Correct. pop removes the value at the given key.

c.

Incorrect. There is no remove method for dictionaries.

d.

Incorrect. There is no insert method for dictionaries.

50. Which of the following are immutable data structures? a.

Dictionaries and lists

b.

Strings and tuples

c.

Integers and floats

d.

Menus and buttons

Answer: b Feedback:

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

59


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

a.

Incorrect. Dictionaries and lists are mutable data structures.

b.

Correct. The contents of strings and tuples cannot be modified.

c.

Correct. Integers and floats are not data structures.

d.

Correct. Menus and buttons are not data structures.

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 33. A group of statisticians at a local college has asked you to create a set of functions that compute the median and mode of a set of numbers, as defined in Section 5.4. Define these functions in a module named stats.py. Also include a function named mean, which computes the average of a set of numbers. Each function should expect a list of numbers as an argument and return a single number. Each function should return 0 if the list is empty. Include a main function that tests the three statistical functions with a given list. (LO: 5.1, 5.2) Solution: See stats.py posted on the Instructor Companion Site.

34. Write a program in the file navigate.py that allows the user to navigate the lines of text in a file. The program should prompt the user for a filename and input the lines of text into a list. The program then enters a loop in which it prints the number of lines in the file and prompts the user for a line number. Actual line numbers range from 1 to the number of lines in the file. If the input is 0, the program quits. Otherwise, the program prints the line associated with that number. (LO: 5.1) Solution: See navigate.py posted on the Instructor Companion Site.

35. Modify the sentence-generator program of Case Study 5.3 (in the file generator.py) so that it inputs its vocabulary from a set of text files at startup. The filenames are nouns.txt, verbs.txt, articles.txt, and prepositions.txt. (Hint: Define a single new function, getWords. This function should expect a

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

60


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

filename as an argument. The function should open an input file with this name, define a temporary list, read words from the file, and add them to the list. The function should then convert the list to a tuple and return this tuple. Call the function with an actual filename to initialize each of the four variables for the vocabulary.) (LO: 5.1, 5.2) Solution: See generator.py posted on the Instructor Companion Site.

36. Make the following modifications to the original sentence-generator program in the file generator.py: a.

The prepositional phrase is optional. (It can appear with a certain probability.)

b.

A conjunction and a second independent clause are optional: The boy took a drink, and the girl played baseball.

c.

An adjective is optional: The girl kicked the red ball with a sore foot.

You should add new variables for the sets of adjectives and conjunctions. (LO: 5.1, 5.2) Solution: See generator.py posted on the Instructor Companion Site.

37. Chapter 4 presented an algorithm for converting from binary to decimal. You can generalize this algorithm to work for a representation in any base. Instead of using a power of 2, this time you use a power of the base. Also, you use digits greater than 9, such as A . . . F, when they occur. Define a function named

repToDecimal in the file convert.py that expects two arguments, a string and an integer. The second argument should be the base. For example, repToDecimal("10", 8) returns 8, whereas

repToDecimal("10", 16) returns 16. The function should use a lookup table to find the value of any digit. Make sure that this table (it is actually a dictionary) is initialized before the function is defined. For its keys, use the 10 decimal digits (all strings) and the letters A . . . F (all uppercase). The value stored with each key should be the integer that the digit represents. (The letter 'A' associates with the integer value 10, and so on.) The main loop of the function should convert each digit to uppercase, look up its value in the table, and use this value in the computation. Include a main function that tests the conversion function with numbers in several bases. (LO: 5.2, 5.3)

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

61


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 5, Lists and Dictionaries

Solution: See convert.py posted on the Instructor Companion Site.

38. Define a function decimalToRep in the file convert.py that returns the representation of an integer in a given base. The two arguments should be the integer and the base. The function should return a string. It should use a lookup table that associates integers with digits. Include a main function that tests the conversion function with numbers in several bases. (LO: 5.2, 5.3) (LO: 5.5, 5.6) Solution: See convert.py posted on the Instructor Companion Site.

39. Write a program in the file unique.py that inputs a text file. The program should print the unique words in the file in alphabetical order. (LO: 5.1) Solution: See unique.py posted on the Instructor Companion Site.

40. A file concordance tracks the unique words in a file and their frequencies. Write a program in the file concordance.py that displays a concordance for a file. The program should output the unique words and their frequencies in alphabetical order. Variations are to track sequences of two words and their frequencies, or n words and their frequencies. (LO: 5.3) Solution: See concordance.py posted on the Instructor Companion Site.

41. In the therapist program, when the patient addresses the therapist personally, the therapist’s reply does not change persons appropriately. To see an example of this problem, test the program with ―you are not a helpful therapist.‖ Fix this problem by repairing the dictionary of replacements in the file doctor.py. (LO: 5.3) Solution: See doctor.py posted on the Instructor Companion Site.

42. Conversations often shift focus to earlier topics. Modify the therapist program in the file doctor.py to support this capability. Add each patient input to a history list. Then, occasionally choose an element at random from this list, change persons, and prepend (add at the beginning) the qualifier ―Earlier you said

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

62


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 6, Design with Functions

that‖ to this reply. Make sure that this option is triggered only after several exchanges have occurred. (LO: 5.1, 5.2) Solution: See doctor.py posted on the Instructor Companion Site.

DEBUGGING EXERCISE SOLUTION Jack is developing a program that calls for converting a list of words to uppercase. He tries out a strategy for this task in the Python shell, as follows:

>>> listOfWords = ["Apple", "orange", "banana"] >>> for word in listOfWords: word = word.upper() >>> listOfWords ['Apple', 'orange', 'banana'] Jack’s strategy does not appear to produce the expected result. Describe the error, explain why it happened, and suggest a correction.

Solution Jack’s for loop access each word in the list, but simply resets the loop variable word to the converted word. This does not reset the word in the list itself to the desired result. To correct the problem, Jack should use an index-based for loop to access and replace the word at each position, as follows:

>>> for index in range(len(listOfWords)): listOfWords[index] = listOfWords[index].upper()

Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 6, DESIGN WITH F UNCTIONS

TABLE OF CONTENTS Exercise Solutions ..................................................................................................................................... 64 Exercise 6.1 ............................................................................................................................................. 64 Exercise 6.2 ............................................................................................................................................. 64 .Exercise 6.3 ............................................................................................................................................ 65

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

63


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 6, Design with Functions

Review Questions Answers....................................................................................................................... 65 Programming Exercises Solutions ........................................................................................................... 69 Debugging Exercise Solution.................................................................................................................... 73

EXERCISE SOLUTIONS EXERCISE 6.1 20. Anne complains that defining functions to use in her programs is a lot of extra work. She says she can finish her programs much more quickly if she just writes them using the basic operators and control statements. State three reasons why her view is shortsighted. Solution: If Anne is writing programs that solve significant problems, the use of functions will help her to (1) eliminate redundant code, (2) hide and control complexity, and (3) divide the work of solving the problems among resources that can be independently tested and maintained. If she does not use functions, her code will likely be difficult to test, verify, and maintain.

21. Explain how an algorithm solves a general class of problems and how a function definition can support this property of an algorithm. Solution: An algorithm typically starts with some input data, processes those data in some manner, and outputs new data. As a general method, an algorithm solves a problem not just for a single data set (a single problem instance) but for all possible data sets for that problem (a general class of problems). A function definition’s code captures the general method of an algorithm, whereas its parameters allow the caller to apply the algorithm to any problem instance (different sets of data)

EXERCISE 6.2 23. Draw a structure chart for one of the solutions to the programming exercises of Chapters 4 and 5. The program should include at least two function definitions other than the main function. Solution: There are several possible charts.

24. Describe the processes of top-down design and stepwise refinement. Where does the design start, and how does it proceed? Solution: Top-down design starts with a main function. This function solves the program’s problem in an abstract way by decomposing the problem into subproblems and calling other functions to solve these. Each of

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

64


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 6, Design with Functions

these functions in turn is designed in the same manner. Stepwise refinement is the process of filling in the details of each function definition.

EXERCISE 6.3 17. Where are module variables, parameters, and temporary variables introduced and initialized in a program? Solution: Module variables are names that are introduced and initialized anywhere in a program, as long as they are not also introduced and initialized within a function definition. Parameters are introduced in a function definition. Required parameters and keyword parameters are initialized in the code that calls the function. If keyword/optional parameters are not initialized in the code that calls the function, they are given default values in the function’s definition. Temporary variables are introduced and initialized in a function definition.

18.

What is the scope of a variable? Give an example.

Solution: The scope of a variable is the area of program text within which it has a particular value. The scope of a function’s parameters is the text of the function’s body.

19. What is the lifetime of a variable? Give an example.

Solution: The lifetime of a variable is the period of program execution during which storage for it exists. The lifetime of a function’s parameter is the duration of a particular call of that function.

REVIEW QUESTIONS ANSWERS 1.

The type of statement that returns a value from a function is the a.

if-else statement

b.

break statement

c.

while statement

d.

return statement

Answer: d Feedback: u.

Incorrect. This statement returns no value.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

65


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 6, Design with Functions

v. Incorrect. This statement returns no value. w. Incorrect. This statement returns no value. x. Correct. This statement returns a value. 2.

When a function does not include a return statement, that function returns the value a.

False

b.

0

c.

None

d.

nothing at all

Answer: c Feedback: a. b. c. d.

3.

Incorrect. False is not the same as None. Incorrect. 0 is not the same as None. Correct. None is the default return value. Incorrect. The return statement always returns a value.

The part of the function that can vary with the context of its call is (are) its a.

return statement

b.

docstring

c.

name

d.

arguments

Answer: d Feedback: a. b. c. d. 4.

Incorrect. The return statement is fixed for all calls of the function. Incorrect. The function name is fixed for all calls of the function. Incorrect. The function docstring is fixed for all calls of the function. Correct. The arguments can vary with the context of the function call.

The part of a function that provides information about its use is (are) its a.

return statement

b.

docstring

c.

set of statements in its body

d.

arguments

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

66


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 6, Design with Functions

Answer: b Feedback: a. b. c. d. 5.

Incorrect. The return statement returns the function’s value. Correct. The docstring includes information about the function’s use. Incorrect. The function’s statements implement the function’s algorithm. Incorrect. The arguments provide data from the function’s caller.

A function’s parameters a.

name variables whose values are the values of the function’s arguments when it is called

b.

are synonymous with the function’s arguments

c.

are always required

d.

are synonymous with the function’s temporary variables

Answer: a Feedback: a. b. c. d. 6.

Correct. Parameters have names, and arguments can be any expressions. Incorrect. Parameters have names, and arguments can be any expressions. Incorrect. Some functions have no parameters. Incorrect. Temporary variables appear in the function’s body, whereas parameters appear in the function’s header, and they serve different roles.

Top-down design is a strategy that a.

develops lower-level functions before the functions that depend on those lower-level functions

b.

starts with the main function and develops the functions on each successive level beneath the main function

c.

develops the functions for a program in a random order

d.

develops the functions for a program in alphabetical order by function name

Answer: b Feedback: y. Incorrect. This would be a bottom-up design strategy. z. Correct. The main function is the top-level function is a program. aa. Incorrect. Random function development not be a strategy at all. bb. Incorrect. The names of functions need not correspond to their roles in a program or to their dependencies on other functions. 7.

The relationships among functions in a top-down design are shown in a a.

syntax diagram

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

67


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 6, Design with Functions

b.

flow diagram

c.

structure chart

d.

table of contents

Answer: c Feedback: u. Incorrect. A syntax diagram depicts the flow of control in a program statement. v. Incorrect. A flow diagram depicts the movement of data between components in a program. w. Correct. A structure chart depicts the dependencies among functions in a program (which functions call which and which data gets transmitted among them). x. Incorrect. A table of contents provides skeletal outline of a book or essay. 8.

The scope of a temporary variable is a.

the statements in the body of the function where the variable is introduced

b.

the entire module in which the variable is introduced

c.

the statements in the body of the function after the statement where the variable is introduced

d.

the time during which storage for the variable is available

Answer: c Feedback: u. v. w. x.

9.

Incorrect. This would be a function parameter. Incorrect. This would be a module variable. Correct. A temporary variable is introduced after the function header. Incorrect. This would be the lifetime of a variable.

The lifetime of a parameter is a.

the duration of program execution

b.

the duration of its function’s execution

c.

approximately one hour

d.

a few microseconds

Answer: b Feedback: u.

Incorrect. This would be the lifetime of a module variable.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

68


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 6, Design with Functions

v.

Correct. Storage for a temporary variable is allocated when the function is called and deallocated when the function returns.

w. Incorrect. The lifetime of a parameter varies with the behavior of the code within which it is embedded. x.

Incorrect. The lifetime of a parameter varies with the behavior of the code within which it is embedded.

10. The required arguments to a function must appear a.

before the optional arguments

b.

after the optional arguments

c.

in any order

d.

either before or after the optional arguments

Answer: a Feedback: u.

Correct. The required arguments must appear to the left of any optional arguments.

v.

Incorrect. Placing an optional argument before a required argument will cause its value to be used for the required argument instead of the required argument’s expected value.

w. Incorrect. Function arguments generally are position-dependent, unless keywords are used. x.

Incorrect. Function arguments generally are position-dependent, unless keywords are used.

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 43. Package Newton’s method for approximating square roots (Case Study 3.6) in a function named newton. This function expects the input number as an argument and returns the estimate of its square root. The script in the file named newton.py should also include a main function that allows the user to compute square roots of inputs until she presses the enter/return key. (LO: 6.2) Solution: See newton.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

69


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 6, Design with Functions

44. Restructure Newton’s method (Case Study 3.6) by decomposing it into three cooperating functions. The task of testing for the limit is assigned to a function named limitReached, whereas the task of computing a new approximation is assigned to a function named improveEstimate. Each function, in the file named newton.py, expects the relevant arguments and returns an appropriate value. (LO: 6.2) Solution: See newton.py posted on the Instructor Companion Site. 45. A list is sorted in ascending order if it is empty or each item except the last one is less than or equal to its successor. Define a predicate isSorted that expects a list as an argument and returns True if the list is sorted, or returns False otherwise. (Hint: For a list of length 2 or greater, loop through the list and compare pairs of items, from left to right, and return False if the first item in a pair is greater.) Include the function in a short tester program in the the file named testsort.py. (LO: 6.2) Solution: See testsort.py posted on the Instructor Companion Site. 46. Modify the grammar checker of this chapter’s Case Study, in the file recognizer.py, so that it recognizes the following additional types of variations in phrases: a.

A verb phrase with no prepositional phrase (example: ―The boy saw the girl‖).

b.

A noun phrase in which the noun is modified by an adjective (example: ―The girl hit the red ball with a bat‖).

c.

A sentence that connects two independent clauses with a conjunction (example: ―The boy threw the ball and the girl hit the ball‖).

You should add new variables for the sets of adjectives and conjunctions. (LO: 6.2) Solution: See recognizer.py posted on the Instructor Companion Site. 47. Design, implement, and test a program in the file named commandinterpreter.py that uses a simple textbased command interpreter. Here is a sample session with the program:

1 Open 2 Save 3 Compile

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

70


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 6, Design with Functions

4 Run 5 Quit Enter a number: 2 Command = Save 1 Open 2 Save 3 Compile 4 Run 5 Quit Enter a number: 3 Command = Compile 1 Open 2 Save 3 Compile 4 Run 5 Quit Enter a number: 5 Command = Quit Have a nice day! The program’s main function a.

Displays a menu of commands.

b.

Accepts an input command from the user.

c.

Calls a function to perform the command.

d.

Repeats steps a through c until the user selects the "Quit" command.

The program should define three other functions, named printMenu, acceptCommand, and

performCommand, to carry out steps a, b, and c, respectively. The function to display the menu © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

71


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 6, Design with Functions

expects a list of menu options as an argument and displays these options prefixed with numbers. The function to accept an input command expects the length of the menu list as an argument. The function repeatedly prompts the user for a number in the range of options and takes inputs until the user enters a number within the range. The function either displays an error message for an invalid input or returns a valid input. The function to perform a command takes a command number and the menu as arguments and displays the selected command in the menu. Test your program with the menu [ "Open", "Save",

"Compile", "Run", "Quit"] and at least one other menu. Note that all menus must include a "Quit" command as the last item in the menu. (LO: 6.2) Solution: See commandinterpreter.py posted on the Instructor Companion Site. 48. Define and test a function myRange in the file named testmyrange.py. This function should behave like Python’s standard range function, with the required and optional arguments, but it should return a list. Do not use the range function in your implementation! (Hints: Study Python’s help on range to determine the names, positions, and what to do with your function’s parameters. Use a default value of None for the two optional parameters. If these parameters both equal None, then the function has been called with just the stop value. If just the third parameter equals None, then the function has been called with a start value as well. Thus, the first part of the function’s code establishes what the values of the parameters are or should be. The rest of the code uses those values to build a list by counting up or down.) (LO: 6.3) Solution: See testmyrange.py posted on the Instructor Companion Site. 49. Add a function named inputFloat to the module testinputfunctions (available in the file named testinputfunctions.py in the Data Files for this chapter). This function behaves like the function

inputInt developed in this chapter but provides for the robust input of floating-point numbers. This function allows digits only or digits and a single decimal point in the input string. Test your new function in this module. (LO: 6.2) Solution: See testinputfunctions.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

72


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 6, Design with Functions

DEBUGGING EXERCISE SOLUTION Jack is developing a function named shuffleString, which rearranges the characters in a given string in random positions. He reasons that he can split the string into a list of its characters, then shuffle this list, and finally join the resulting list back into a string. He tries out his strategy for this task in the Python shell, as follows:

>>> import random >>> def shuffleString(theString): return "".join(random.shuffle(list(theString))) >>> shuffleString("Apples are red") Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> shuffleString("Apples are red") File "<pyshell#2>", line 2, in shuffleString return "".join(random.shuffle(list(theString))) TypeError: can only join an iterable Jack’s strategy does not appear to produce the expected result. Determine the cause of the error and correct it. Solution The error occurs within the return statement of the function. Jack selects the appropriate operations to create a list of characters from the string, shuffle this list, and join the list back into a string. However, the

random.shuffle function does not return a list. A quick glance at Python’s help shows that random.shuffle returns None, which is not a value that the string method join expects to work with; random.shuffle instead just modifies its argument list. Jack has tried to implement his strategy in one line of clever code. The join method expects an iterable object as is argument, which will allow the method to visit each

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

73


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 7, Design with Recursion

string in a sequence of strings. A correct implementation would be more deliberate, placing the three operations in separate statements, as follows:

>>> import random >>> def shuffleString(theString): theList = list(theString) random.shuffle(theList) return "".join(theList) >>> shuffleString("Apples are red") ' rpaspdreele A'

Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 7, DESIGN WITH RECURSION

TABLE OF CONTENTS Exercise Solutions ..................................................................................................................................... 75 Exercise 7.1 ............................................................................................................................................. 75 Exercise 7.2 ............................................................................................................................................. 76 Review Questions Answers....................................................................................................................... 77 Programming Exercises Solutions ........................................................................................................... 81 Debugging Exercise Solution.................................................................................................................... 83

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

74


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 7, Design with Recursion

EXERCISE SOLUTIONS EXERCISE 7.1 22. In what way is a recursive design different from top-down design? Solution: There is only one function developed in recursive design. At each level, this function decides whether to solve a problem directly (a base case) or solve a problem by running itself with a smaller instance of the same problem (a recursive case).

23. The factorial of a positive integer n, fact(n), is defined recursively as follows: fact(n) = 1, when n = 1 fact(n) = n * fact(n - 1), otherwise Define a recursive function fact that returns the factorial of a given positive integer. Solution:

def fact(n): if fact == 1: return 1 else: return n * fact(n – 1) 24. Describe the costs and benefits of defining and using a recursive function. Solution: Recursive functions typically require extra memory and processing time to manage the information needed for function calls, such as the values of parameters, the returned values, and the return addresses. The benefits are that recursive designs can be very simple and can naturally reflect the structure of the data to be processed or the problem to be solved.

25. Explain what happens when the following recursive function is called with the value 4 as an argument:

def example(n): if n > 0: print(n) example(n - 1) Solution: The numbers 1, 2, 3, and 4 are printed on separate lines.

26. Explain what happens when the following recursive function is called with the value 4 as an argument:

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

75


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 7, Design with Recursion

def example(n): if n > 0: print(n) example(n) else: example(n - 1) Solution: The function is infinitely recursive with this data value because the call that decrements the argument is never reached. The function continues to print the number 4 until the system runs out of memory to support the recursion. 27. Explain what happens when the following recursive function is called with the values "hello" and 0 as arguments:

def example(aString, index): if index < len(aString): example(aString, index + 1) print(aString[index], end = "") Solution:

Because the print function occurs after the recursive call, the characters in the string will be printed in reverse order. 28. Explain what happens when the following recursive function is called with the values "hello" and 0 as arguments:

def example(aString, index): if index == len(aString): return "" else: return aString[index] + example(aString, index + 1) Solution:

The function returns a string that is a copy of the argument string.

EXERCISE 7.2 25. Write the code for a mapping that generates a list of the absolute values of the numbers in a list named numbers. Solution:

list(map(abs, numbers))

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

76


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 7, Design with Recursion

26. Write the code for a filtering that generates a list of the positive numbers in a list named numbers. You should use a lambda to create the auxiliary function. Solution:

list(filter(lambda x: x > 0, numbers)) 27. Write the code for a reducing that creates a single string from a list of strings named words. Solution:

reduce(lambda x, y: x + y, words) 28. Modify the summation function presented in Section 7.1 so that it includes default arguments for a step value and a function. The step value is used to move to the next value in the range. The function is applied to each number visited, and the function’s returned value is added to the running total. The default step value is 1, and the default function is lambda that returns its argument (essentially an identity function). An example call of this function is summation(l, 100, 2, math.sqrt), which returns the sum of the square roots of every other number between 1 and 100. The function can also be called as usual, with just the bounds of the range. Solution:

def summation(lower, upper, step = 1, func = lambda x: x): result = 0 while lower <= upper: result += func(lower) lower += step return result 29. Three versions of the summation function have been presented in this chapter. One uses a loop, one uses recursion, and one uses the reduce function. Discuss the costs and benefits of each version, in terms of programmer time and computational resources required. Solution: The first version of summation, which uses a loop, requires the programmer to develop and verify the loop’s logic. This process can be more error-prone than it would be for the recursive version or the version that uses reduce. The recursive version can require more processing time and memory during execution. The version that uses reduce is the easiest to read, write, and verify.

REVIEW QUESTIONS ANSWERS 11. The part of a recursive function that ends the recursive process is called the e.

recursive step

f.

base case

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

77


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 7, Design with Recursion

g.

loop continuation condition

h.

loop update

Answer: b Feedback: cc. Incorrect. The recursive step continues the recursive process. dd. Correct. The base case checks for the termination condition and returns a simple value if it’s true. ee. Incorrect. This condition continues a loop if it’s true. ff. Incorrect. This step modifies a loop control variable. 12. The part of a recursive function that continues the recursive process is called the a.

recursive step

b.

base case

c.

loop continuation condition

d.

loop update

Answer: b Feedback: a. b. c. d.

Correct. The recursive step continues the recursive process. Incorrect. The base case checks for the termination condition and returns a simple value if it’s true. Incorrect. This condition continues a loop if it’s true. Incorrect. This step modifies a loop control variable.

13. A recursive function usually a.

runs faster than the equivalent loop

b.

runs more slowly than the equivalent loop

c.

runs at the same speed as the equivalent loop

d.

uses the same amount of memory than the equivalent loop

Answer: b Feedback: a. b. c. d.

Incorrect. Recursive functions require extra running time to support call stack manipulation. Correct. Recursive functions require extra running time to support call stack manipulation. Incorrect. Recursive functions require extra running time to support call stack manipulation. Incorrect. Recursive functions require extra memory to support call stack manipulation.

14. When a recursive function is called, the values of its arguments and its return address are placed in a e.

list

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

78


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 7, Design with Recursion

f.

dictionary

g.

set

h.

stack frame

Answer: d Feedback: y. Incorrect. The runtime support for recursion is a stack of frames. z. Incorrect. The runtime support for recursion is a stack of frames. aa. Incorrect. The runtime support for recursion is a stack of frames. bb. Correct. The runtime support for recursion is a stack of frames. 15. The keyword used to construct an anonymous function is named e.

while

f.

if

g.

return

h.

lambda

Answer: c Feedback: y. Incorrect. This keyword begins a loop statement. z. Incorrect. This keyword begins a selection statement. aa. Incorrect. This keyword begins a return statement. bb. Correct. This keyword begins a lambda function. 16. The function that creates a sequence of the values by applying another function to a sequence of arguments is named a.

filter

b.

map

c.

reduce

d.

range

Answer: c Feedback: a.

Incorrect. This names a function that applies a Boolean function to a sequence of arguments and returns a sequence of values that pass this test.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

79


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 7, Design with Recursion

b. c. d.

Correct. This names a function that applies a function to a sequence of arguments and returns a sequence of values. Incorrect. This names a function that boils a sequence of values down to a single value by applying a function of two arguments to each value and the result of a previous application. Incorrect. This names a function that returns a sequence of integers in a range specified by a lower bound, an upper bound, and a step value.

17. The expression list(map(math.sqrt, [9, 25, 36])) evaluates to a.

70

b.

[81, 625, 1296]

c.

[3.0, 5.0, 6.0]

d.

[]

Answer: c Feedback: a. b. c. d.

Incorrect. This is not a list. Incorrect. This is a list of the squares of the numbers in the argument list. Correct. This is a list of the square roots of the numbers in the argument list. Incorrect. The argument list is not empty.

18. The expression list(filter(lambda x: x > 50, [34, 65, 10, 100])) evaluates to a.

[]

b.

[65, 100]

c.

[34, 65, 10, 100]

d.

[34, 10]

Answer: b Feedback: y. Incorrect. There are two numbers greater than 50 in the argument list. z. Correct. These are the numbers greater than 50 in the argument list. aa. Incorrect. There are two numbers less than or equal to 50 in the argument list. bb. Incorrect. These numbers are less than 50.

19. The expression reduce(max, [34, 21, 99, 67, 10]) evaluates to

a. 231

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

80


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 7, Design with Recursion

b.

0

c.

99

d.

100

Answer: c Feedback: a. b. c. d.

Incorrect. 231 is not in the list but is the sum of the numbers in the list. Incorrect. 0 is not in the list. Correct. 99 is the largest number in the list. Incorrect. 100 is not in the list.

20. A data structure used to implement a jump table is a e.

list

f.

tuple

g.

dictionary

h.

string

Answer: c Feedback: y. z.

Incorrect. A list is a sequence of single values, and so it does not support the lookup of functions by name. Incorrect. A tuple is a sequence of single values, and so it does not support the lookup of functions by name. aa. Correct. A dictionary supports a jump table, where the keys are function names and the values are the functions associated with those names. bb. Incorrect. A string is a sequence of characters.

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 50. Convert Newton’s method for approximating square roots in Programming Exercise 6.1 (in the file newton.py) to a recursive function named newton. (Hint: The estimate of the square root should be passed as a second argument to the function.) (LO: 7.1) Solution: See newton.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

81


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 7, Design with Recursion

51. Restructure Newton’s method (Case Study 3.2) by decomposing it into three cooperating functions. The

newton function should use the recursive strategy of Programming Exercise 7.1 (in the file newton.py). The task of testing for the limit is assigned to a function named limitReached, whereas the task of computing a new approximation is assigned to a function named improveEstimate. Each function expects the relevant arguments and returns an appropriate value. (LO: 7.1) Solution: See newton.py and newtoniterative.py posted on the Instructor Companion Site. 52. Add a command to this chapter’s case study program (in the file filesys.py) that allows the user to view the contents of a file in the current working directory. When the command is selected, the program should display a list of filenames and a prompt for the name of the file to be viewed. Be sure to include error recovery. (LO: 7.1) Solution: See filesys.py posted on the Instructor Companion Site. 53. Write a recursive function that expects a pathname as an argument. The pathname can be either the name of a file or the name of a directory. If the pathname refers to a file, its name is displayed, followed by its contents. Otherwise, if the pathname refers to a directory, the function is applied to each name in the directory. Test this function in a new program (in the file viewfiles.py). (LO: 7.1) Solution: See viewfiles.py posted on the Instructor Companion Site. 54. Lee has discovered what he thinks is a clever recursive strategy for printing the elements in a sequence (string, tuple, or list). He reasons that he can get at the first element in a sequence using the 0 index, and he can obtain a sequence of the rest of the elements by slicing from index 1. This strategy is realized in a function that expects just the sequence as an argument. If the sequence is not empty, the first element in the sequence is printed and then a recursive call is executed. On each recursive call, the sequence argument is sliced using the range 1:. Here is Lee’s function definition:

def printAll(seq): if seq: print(seq[0]) printAll(seq[1:])

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

82


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 7, Design with Recursion

Write a script (in the file testprintlist.py) that tests this function and add code to trace the argument on each call. Does this function work as expected? If so, explain how it works, and describe any hidden costs in running it. (LO: 7.1) Solution: See testprintlist.py posted on the Instructor Companion Site. 55. Write a program (in the file average.py) that computes and prints the average of the numbers in a text file. You should make use of two higher-order functions to simplify the design. (LO: 7.2) Solution: See average.py posted on the Instructor Companion Site. 56. The grammar checker of Case Study: Recognizing Sentences in Chapter 6 (in the file recognizer.py) does not handle sentences with an arbitrary number of independent clauses. Use the modified grammar rule discussed in Section 7.1 to design, implement, and test a recursive sentence function that performs this task. (LO: 7.1) Solution: See recognizer.py posted on the Instructor Companion Site. 57. Suppose that Python does not include the higher-order functions map, filter, and reduce. Define these three functions, named myMap, myFilter, and myReduce, in a new module named hof (in the file hof.py). The myMap and myFilter functions expect a function of one argument and a list as arguments and return a list of the results. The myReduce function expects a function of two arguments and a nonempty list as arguments and returns a single value. Test your functions in a short tester program (in the file testhof.py) that compares their behavior to that of Python’s own map, filter, and reduce functions. (LO: 7.2) Solution: See hof.py and testhof.py posted on the Instructor Companion Site.

DEBUGGING EXERCISE SOLUTION Jill points out to Jack that English grammar allows a noun to be modified by zero or more adjectives. Examples are ―The girl hit the ball,‖ ―The girl hit the red ball,‖ and ―The girl hit the little red ball.‖ She asks Jack to design and implement a function to generate noun phrases based on the following grammar rules:

nounphrase = article [adjectivephrase] noun

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

83


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 7, Design with Recursion

adjectivephrase = adjective [adjectivephrase] where an adjective phrase is one or more adjectives (remember that the [] brackets indicate an optional item in a grammar rule). Jack’s code for the nounPhrase and adjectivePhrase functions follows:

#nounphrase = article [adjectivephrase] noun def nounPhrase(): """Builds and returns a noun phrase.""" return random.choice(articles) + " " + \ adjectivePhrase() + " " + random.choice(nouns)

#adjectivehrase = adjective [adjectivephrase] def nounPhrase(): """Builds and returns an adjective phrase.""" return random.choice(adjective) + " " + adjectivePhrase() When Jack tests the nounPhrase function, the PVM halts the program with a RecursionError. Explain why this error occurs and describe how to correct it. Solution The RecursionError in Jack’s code occurs in the return statement of his adjectivePhrase function. This function selects an adjective from the set of adjectives and then adds it to another adjective phrase, which selects another adjective and adds it to another adjective phrase, and so on, until the PVM runs out of memory to support the potentially infinite number of recursive calls of the adjectivePhrase function. To correct this error, Jack must come up with a base case that can stop the recursive process. The grammar rule says that an adjective phrase has at least one adjective and possibly more. Therefore, the function should begin by selecting an adjective, as before, but make a recursive call only if a random number lies in a certain range. If that range is small, more adjectives will likely be generated, but the recursive process will stop eventually. This strategy is similar to the one for the modified nounPhrase and sentence functions discussed in Section 7.1.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

84


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 7, Design with Recursion

Another error occurs in Jack’s nounPhrase function. The rule for this phrase says that an adjective phrase is optional (zero or more adjectives), but Jack’s code calls the adjectivePhrase function, which generates at least one adjective anyway. To correct this error, Jack’s code must call this function only if a random number lies within a certain range. Here is the code for a version of these two functions that includes one or more adjectives 25 percent of the time:

#nounphrase = article [adjectivephrase] noun def nounPhrase(): """Builds and returns a noun phrase.""" article = random.choice(articles) noun = random.choice(nouns) if random.randint(1, 4) == 1:

#25% probability

return article + " " + adjectivePhrase() + " " + noun else: return article + " " + noun

#adjectivephrase = adjective [adjectivephrase] def adjectivePhrase(): """Builds and returns an adjective phrase.""" adjective = random.choice(adjective) if random.randint(1, 4) == 1:

#25% probability

return adjective + " " + adjectivePhrase() else: return adjective

Solution and Answer Guide © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

85


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 8, SIMPLE GRAPHICS AND IMAGE PROCESSING

TABLE OF CONTENTS Exercise Solutions ..................................................................................................................................... 86 Exercise 8.1 ............................................................................................................................................. 86 Exercise 8.2 ............................................................................................................................................. 87 Review Questions Answers....................................................................................................................... 89 Programming Exercises Solutions ........................................................................................................... 93 Debugging Exercise Solution.................................................................................................................... 97

EXERCISE SOLUTIONS EXERCISE 8.1 29. Explain the importance of the interface of a class of objects. Solution: The interface of a class of objects is the set of methods available to their users. As such, the interface describes the behavior of the objects and gives users the information they need to know in order to use them correctly.

30. What is object instantiation? What are the options at the programmer’s disposal during this process?

Solution: Object instantiation is the process whereby an object of a given class is created. During this process, the object’s attributes are given initial values. The user of an object sometimes has the option of supplying these values during the instantiation process. 31. Add a function named circle to the polygons module. This function expects the same arguments as the square and hexagon functions. The function should draw a circle. (Hint: The loop iterates 360 times.) Solution:

def circle(t, length): for x in range(360): t.forward(length) t.left(1)

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

86


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

32. The functions that draw polygons in the polygons module have the same pattern, varying only in the number of sides (iterations of the loop). Factor this pattern into a more general function named polygon, which takes the number of sides as an additional argument.

Solution:

def polygon(t, length, sides): for x in range(sides): t.forward(length) t.left(360 / sides) 33. Turtle graphics windows do not automatically expand in size. What do you suppose happens when a Turtle object attempts to move beyond a window boundary?

Solution: The lines drawn by the turtle are clipped at the window’s boundary, but you can zoom the window or move its scrollbars to view the lines drawn on the canvas beyond the window’s initial boundary. 34. The Turtle class includes a method named circle. Import the Turtle class, run help(Turtle.circle), and study the documentation. Then use this method to draw a filled circle and a half moon.

Solution:

# To draw a disk or filled circle: from turtle import Turtle disk = Turtle() disk.hideturtle() disk.begin_fill() disk.fillcolor("red") disk.circle(50) disk.end_fill() # To draw a half moon: from turtle import Turtle moon = Turtle() moon.hideturtle() moon.begin_fill() moon.fillcolor("yellow") moon.circle(50, 180) moon.end_fill().

EXERCISE 8.2 30. Explain the advantages and disadvantages of lossless and lossy image file-compression schemes.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

87


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

Solution: A lossless compression scheme preserves all of the digital information acquired during sampling. The disadvantage is that this requires more memory, which might be at a premium in miniature devices or for transmission on a network.

31. The size of an image is 1680 pixels by 1050 pixels. Assume that this image has been sampled using the RGB color system and placed into a raw image file. What is the minimum size of this file in megabytes? (Hint: There are 8 bits in a byte, 1024 bits in a kilobyte, and 1000 kilobytes in a megabyte.) Solution: 5.16797 megabytes

32. Describe the difference between Cartesian coordinates and screen coordinates. Solution: The origin of a Cartesian coordinate system is at the center. x and y coordinates increase to the right of the y axis and above the x axis, respectively, and decrease to the left of the y axis and below the x axis, respectively. The origin of a screen coordinate system is at the upper left corner of the display or window. The x and y coordinates increase to the right of the y axis and below the x axis, respectively, and decrease to the left of the y axis and above the x axis, respectively.

33. Describe how a row-major traversal visits every position in a two-dimensional grid. Solution: A row-major traversal begins at the first row and moves across the columns in that row, starting from the leftmost column, until it reaches the last column. It then repeats this process for each row after the first one.

34. How would a column-major traversal of a grid work? Write a code segment that prints the positions visited by a column-major traversal of a 2-by-3 grid. Solution: A column-major traversal would begin with the first column and move down the rows in that column, starting from the first row, until it reaches the last row. It then repeats this process for each column after the first one.

for column in range(3): for row in range(2): print((column, row))

35. Explain why one would use the clone method with a given object. Solution:

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

88


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

The clone method is used to obtain a copy of an object. It would be used when the programmer wants to obtain a distinct object with the same attributes as the original object. The attributes of the second object can then be modified without changing those of the original object.

36. Why does the blur function need to work with a copy of the original image? Solution: The blur function must reset some pixels in an image as it traverses it. The information used during this process must come from the neighbors of these pixels. But the reset pixels in turn are used later in the process, so this information would be lost if the pixels were reset in the original image. That is why information must be read from one image and written to another.

REVIEW QUESTIONS ANSWERS 21. The interface of a class is the set of all its i.

objects

j.

attributes

k.

methods

l.

functions

Answer: c Feedback: gg. Incorrect. Objects are instances of a class. hh. Incorrect. Attributes are data belonging to an object. ii. Correct. Methods are the operations in a class’s interface. jj. Incorrect. Classes do not define functions. 22. The state of an object consists of i.

its class of origin

j.

the values of all of its attributes

k.

its physical structure

l.

its methods

Answer: b Feedback: cc. Incorrect. A class specifies the kind of attributes and operations on all of its objects. dd. Correct. Attribute values belong to individual objects.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

89


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

ee. Incorrect. Objects are not physical things, but software representations. ff. Incorrect. Methods specify an object’s behavior. 23. Instantiation is a process that i.

compares two objects for equality

j.

builds a string representation of an object

k.

creates a new object of a given class

l.

destroys an object

Answer: c Feedback: cc. Incorrect. This is the comparison operation. dd. Incorrect. This is the str function. ee. Correct. An object is an instance of a class. ff. Incorrect. There is no operation to destroy an object.

24. The print function a.

creates a new object

b.

copies an existing object

c.

prints a string representation of an object

d.

compares two objects

Answer: c Feedback: cc. Incorrect. This is instantiation. dd. Incorrect. This is the clone method. ee. Correct. print calls str on the object and prints the string returned. ff. Incorrect. print performs no comparisons.

25. The clone method a.

creates a new object

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

90


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

b.

copies an existing object

c.

returns the string representation of an object

d.

returns a reference to the original object

Answer: b Feedback: a.

Incorrect. This is instantiation.

b.

Correct. clone returns a new object with the same attributes as the original object.

c.

Incorrect. This is the str function.

d.

Incorrect. This is a variable reference.

26. The origin (0, 0) in a screen coordinate system is at the i.

center of the window

j.

upper-left corner of the window

k.

upper-right corner of the window

l.

lower-left corner of the window

Answer: b Feedback: cc. Incorrect. This is the origin of a Cartesian coordinate system. dd. Correct. Positive x and y coordinates extend to the left and down from position (0, 0) in the upper left corner. ee. Incorrect. The position in the upper right corner is (the largest visible x position, 0). ff. Incorrect. The position in the upper right corner is (the largest visible x position, the largest visible y position). 27. A row-major traversal of a two-dimensional grid visits all of the positions in a a.

row before moving to the next row

b.

column before moving to the next column

c.

row from the last position to the first

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

91


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

d.

column from the last position to the first

Answer: a Feedback: a.

Correct. The order is to visit all the columns in a row, then move on to the next row.

b.

Incorrect. This would be column-major order.

c.

Incorrect. This would visit rows from bottom to top.

d.

Incorrect. This would visit columns from right to left.

28. In a system of 256 unique colors, the minimum number of bits needed to represent each color is a.

4

b.

8

c.

16

d.

32

Answer: b Feedback: a.

Incorrect. 4 bits would represent up to 24 or 16 colors.

b.

Correct. 256 is 28, so 8 bits represents values 0 through 255.

c.

Incorrect. 16 bits would represent up to 216 or 65,536 colors.

d.

Incorrect. 32 bits would represent up to 232 or 4,294,967,296 colors.

29. In the RGB system, where each color contains three components with 256 possible values each, the number of bits needed to represent each color is a.

4

b.

24

c.

256

d.

512

Answer: b Feedback: a.

Incorrect. This is too few bits.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

92


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

b.

Correct. 8 bits are needed to represent 256 values, and 24 is the sum of 8 and 8 and 8.

c.

Incorrect. This is more than needed.

d.

Incorrect. This is more than needed.

30. The process whereby analog information is converted to digital information is called a.

recording

b.

sampling

c.

filtering

d.

compressing

Answer: b Feedback: a.

Incorrect. Recording can produce analog information.

b.

Correct. Each analog signal at a given position in space (color in a visual field) or time (amplitude and frequency of sound) is converted to the nearest discrete digital value during sampling.

c.

Incorrect. Filtering removes information.

d.

Incorrect. Compressing reduces the amount of physical space required to store information.

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 58. Define a function drawCircle (in the file circle.py). This function should expect a Turtle object, the coordinates of the circle’s center point, and the circle’s radius as arguments. The function should draw the specified circle. The algorithm should draw the circle’s circumference by turning 3 degrees and moving a given distance 120 times. Calculate the distance moved with the formula 2.0 * p * radius / 120.0. (LO: 8.1) Solution: See circle.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

93


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

59. Modify this chapter’s case study program (the c-curve in the file ccurve.py) so that it draws the line segments using random colors. (LO: 8.1) Solution: See ccurve.py posted on the Instructor Companion Site.

60. The Koch snowflake is a fractal shape. At level 0, the shape is an equilateral triangle. At level 1, each line segment is split into four equal parts, producing an equilateral bump in the middle of each segment. Figure 8-15 shows these shapes at levels 0, 1, and 2. At the top level, the script uses a function

drawFractalLine to draw three fractal lines. Each line is specified by a given distance, direction (angle), and level. The initial angles are 0, –120, and 120 degrees. The initial distance can be any size, such as 200 pixels. The function drawFractalLine is recursive. If the level is 0, then the turtle moves the given distance in the given direction. Otherwise, the function draws four fractal lines with one-third of the given distance, angles that produce the given effect, and the given level minus 1. Write a script (in the file koch.py) that draws the Koch snowflake. (LO: 8.1) Solution: See koch.py posted on the Instructor Companion Site

61. The twentieth-century Dutch artist Piet Mondrian developed a style of abstract painting that exhibited simple recursive patterns. To generate such a pattern with a computer, one would begin with a filled rectangle in a random color and then repeatedly fill two unequal subdivisions with random colors, as shown in Figure 7-16. As you can see, the algorithm continues the process of subdivision until an ―aesthetically right moment‖ is reached. In this version, the algorithm divides the current rectangle into portions representing one-third and two-thirds of its area and alternates these subdivisions along the horizontal and vertical axes. Design, implement, and test a script (in the file mondrian.py) that uses a recursive function to draw these patterns. (LO: 8.1) Solution: See mondrian.py posted on the Instructor Companion Site

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

94


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

62. Define and test a function named posterize (in the file posterize.py) This function expects an image and a tuple of RGB values as arguments. The function modifies the image like the blackAndWhite function, but it uses the given RGB values instead of black. (LO: 8.2) Solution: See posterize.py posted on the Instructor Companion Site

63. Define a second version of the grayscale function (in the file grayscale.py) that uses the allegedly crude method of simply averaging each RGB value. Test the function by comparing its results with those of the other version discussed in this chapter. (LO: 8.2) Solution: See grayscale.py posted on the Instructor Companion Site

64. Inverting an image makes it look like a photographic negative. Define and test a function named invert (in the file invert.py) This function expects an image as an argument and resets each RGB component to 255 minus that component. Be sure to test the function with images that have been converted to grayscale and black and white as well as color images. (LO: 8.2) Solution: See invert.py posted on the Instructor Companion Site

65. Old-fashioned photographs from the nineteenth century are not quite black and white and not quite color, but seem to have shades of gray, brown, and blue. This effect is known as sepia, as shown in Figure 8-17. Old-fashioned photographs from the nineteenth century are not quite black and white and not quite color, but seem to have shades of gray, brown, and blue. This effect is known as sepia, as shown in Figure 8-17. Write and test a function named sepia (in the file sepia.py) that converts a color image to sepia. This function should first call grayscale to convert the color image to grayscale. A code segment for transforming the grayscale values to achieve a sepia effect follows. Note that the value for green does not change. (LO: 8.2)

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

95


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

(red, green, blue) = image.getPixel(x, y) if red < 63: red = int(red * 1.1) blue = int(blue * 0.9) elif red < 192: red = int(red * 1.15) blue = int(blue * 0.85) else: red = min(int(red * 1.08), 255) blue = int(blue * 0.93) Solution: See sepia.py posted on the Instructor Companion Site.

66. Darkening an image requires adjusting its pixels toward black as a limit, whereas lightening an image requires adjusting them toward white as a limit. Because black is RGB (0, 0, 0) and white is RGB (255, 255, 255), adjusting the three RGB values of each pixel by the same amount in either direction will have the desired effect. Of course, the algorithms must avoid exceeding either limit during the adjustments. Lightening and darkening are actually special cases of a process known as color filtering. A color filter is any RGB triple applied to an entire image. The filtering algorithm adjusts each pixel by the amounts specified in the triple. For example, you can increase the amount of red in an image by applying a color filter with a positive red value and green and blue values of 0. The filter (20, 0, 0) would make an image’s overall color slightly redder. Alternatively, you can reduce the amount of red by applying a color filter with a negative red value. Once again, the algorithms must avoid exceeding the limits on the RGB values. Develop three algorithms for lightening, darkening, and color filtering as three related Python functions,

lighten, darken, and colorFilter (in the file colorfilter.py) The first two functions should expect an image and a positive integer as arguments. The third function should expect an image and a tuple of integers (the RGB values) as arguments. The following session shows how these functions can be used with the images image1, image2, and image3, which are initially transparent.

>>> image1 = Image(100, 50) >>> image2 = Image(100, 50) >>> image3 = Image(100, 50)

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

96


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

>>> darken(image1, 128)

# Converts to gray

>>> darken(image2, 64)

# Converts to dark gray

>>> colorFilter(image3, (255, 0, 0))

# Converts to red

Note that most of the code to change the image is in the function colorFilter. (LO: 8.2) Solution: See colorfilter.py posted on the Instructor Companion Site.

67. The edge-detection function described in this chapter returns a black-and-white image. Think of a similar way to transform color values so that the new image is still in its original colors but the outlines within it are merely sharpened. Then, define a function named sharpen (in the file sharpen.py) that performs this operation. The function should expect an image and two integers as arguments. One integer should represent the degree to which the image should be sharpened. The other integer should represent the threshold used to detect edges. (Hint: A pixel can be darkened by making its RGB values smaller.) (LO: 8.2) Solution: See sharpen.py posted on the Instructor Companion Site.

DEBUGGING EXERCISE SOLUTION Jill is developing an image processing program that creates artworks with random colors. The inputs to the program are the width and height of a new image and the name of a file to which the image should be saved. Here is the code for Jill’s program:

""" File: randomart.py Generates and saves images with random colors. """

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

97


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

from images import Image import random

def main(): """Generates and saves images with random colors. Inputs: The image's width, height, and output file name.""" width = int(input("Enter the image's width: ")) height = int(input("Enter the image's height: ")) fileName = input("Enter the image's file name: ")

image = Image(width, height) for y in range(image.getHeight()): for x in range(image.getWidth()): r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) image.setPixel(x, y, (r, g, b))

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

98


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

print("Close the image window to quit. ") image.draw() image.save(fileName)

if __name__ == "__main__": main() When Jill runs the program, she enters her inputs and views the image before it’s saved. But when she closes the window and the program attempts to save the image, Python raises than error that the image has too many colors, as shown in Figure 8.18. Explain why this error occurs and describe how it can be corrected. Jack reminds Jill that the GIF format supports at most 256 unique colors. Solution The error occurs when the program attempts to save the pixels in the grid to a GIF file. If there are more than 256 pixels in the grid, it is possible that it will contain more than 256 unique colors, which would violate the requirements of the GIF format, which can support at most 255 unique colors in a given image. The reason that Jill’s code might generate more than 256 colors is that her code for creating a color, which randomly selects each color component from 256 possible values, selects a color at random from the complete RGB range of 224 possible color values. To correct this error, Jill must select colors from a list of only 255 possible random colors. The solution first creates a list of 255 randomly generated colors (from 224 possible RGB values) and then selects one of these colors at random to fill in the image’s pixels. Here is the revised program:

"""

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

99


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 8, Simple Graphics and Image Processing

File: randomart.py Generates and saves images with random colors from a table of 256 possible random colors. """

from images import Image import random

def main(): """Generates and saves images with random colors. Inputs: The image's width, height, and output file name.""" width = int(input("Enter the image's width: ")) height = int(input("Enter the image's height: ")) fileName = input("Enter the image's file name: ")

# Create a table of 256 unique colors for GIF image colors = [] while len(colors) < 255: r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) if not (r, g, b) in colors: colors.append((r, g, b))

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

100


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

image = Image(width, height) for y in range(image.getHeight()): for x in range(image.getWidth()): color = random.choice(colors) image.setPixel(x, y, color)

print("Close the image window to quit. ") image.draw() image.save(fileName)

if __name__ == "__main__": main()

Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 9, GRAPHICAL USER INTERFACES

TABLE OF CONTENTS Exercise Solutions ................................................................................................................................... 102 Exercise 9.1 ........................................................................................................................................... 102 Exercise 9.2 ........................................................................................................................................... 102 Exercise 9.3 ........................................................................................................................................... 102 Exercise 9.4 ........................................................................................................................................... 104 Exercise 9.5 ........................................................................................................................................... 104 Exercise 9.6 ........................................................................................................................................... 105 Review Questions Answers..................................................................................................................... 106 Programming Exercises Solutions ......................................................................................................... 110 Debugging Exercise Solution.................................................................................................................. 113

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

101


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

EXERCISE SOLUTIONS EXERCISE 9.1 35. Describe two fundamental differences between terminal-based user interfaces and GUIs. Solution: A terminal-based interface supports the input and output of text only, whereas a GUI supports the display of graphical images and accepts inputs from a pointing device as well. A terminal-based interface guides the user through a sequence of inputs, whereas a GUI is event-driven, allowing the user to enter inputs in any order before the user accepts these by pressing a button.

36. Give an example of one application for which a terminal-based user interface is adequate and one example that lends itself best to a GUI.

Solution: Text messaging is an example of an application for which a terminal-based interface is perfectly adequate. A GUI is more suitable for an image manipulation program.

EXERCISE 9.2 37. Describe what usually happens in the __init__ method of a main window class. Solution: The __init__ method in a main window class runs __init__ on the parent frame and then instantiates the widgets for this window. Finally, it arranges these widgets in the window’s grid. 38. Explain why it’s a good idea to make a new class a subclass of an existing class. Solution: When you make a new class a subclass of an existing class, you inherit all the methods and data of the parent class, and of any other ancestor classes, for free. This means that you do not have to reinvent this behavior and state.

EXERCISE 9.3 1.

Write a code segment that centers the labels RED, WHITE, and BLUE vertically in a GUI window. The text of each label should have the color that it names, and the window’s background color should be green. The background color of each label should also be green. Solution:

EasyFrame.__init__(self, background = "green")

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

102


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

redLabel = self.addLabel(text = "RED", row = 0, column = 0, sticky = "NSEW", foreground = "red", background = "green") whiteLabel = self.addLabel(text = "WHITE", row = 1, column = 0, sticky = "NSEW", foreground = "white", background = "green") blueLabel = self.addLabel(self, text = "BLUE" row = 2, column = 0, sticky = "NSEW", foreground = "blue", background = "green") 2.

Run the demo program fontdemo.py to explore the font families available on your system. Then write a code segment that centers the labels COURIER, HELVETICA, and TIMES horizontally in a GUI window. The text of each label should be the name of the font family associated with the text. Substitute a different font family if necessary. Solution:

cFont = tkinter.font.Font(family = "Courier") hFont = tkinter.font.Font(family = "Helvetica") tFont = tkinter.font.Font(family = "Times") addLabel(text = "COURIER", row = 0, column = 0, sticky = "NSEW", font = cFont) addLabel(text = "HELVETICA", row = 1, column = 0, sticky = "NSEW", font = hFont) addLabel(text = "TIMES", row = 2, column = 0, sticky = "NSEW", font = tFont) 3.

Write a GUI program that uses a loop to create and place nine labels into a 3-by-3 grid. The text of each label should be its coordinates in the grid, starting with (0, 0) in the upper left corner. Each label should be centered in its grid cell. You should use a nested for loop in your code. Then modify and run the same program to display labels in an 8 by 10 grid. Solution:

for row in range(3): for column in range(3): self.addButton(text = str((row, column)), row = row, column = column, sticky = "NSEW") To modify the code for an 8 by 10 grid, the outer loop would use range(8) and the nested loop would use range(10). 4.

Jill has a plan for a window layout with two rows of widgets. The first row contains two widgets, and the second row contains four widgets. Describe how she can align the widgets so that they are evenly spaced in each row. Solution:

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

103


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

The grid will be 2 rows by 4 columns. Jill should center each widget with a sticky attribute of NSEW, and she should add the widgets in the first row to columns 0 and 2, each with a columnspan of 2.

5.

Describe the procedure for setting up the display of an image in a window. Solution: There are three steps to display an image in a window: first, add a label to the window, with an empty string as the label’s text attribute; second, set an instance variable to a new PhotoImage loaded from an image file (in GIF format); and third, set the label’s image attribute to the value of this instance variable.

EXERCISE 9.4 1.

Explain what happens when a user clicks a command button in a fully functioning GUI program. Solution: When the user clicks a command button, the event-handler method associated with that button is triggered. The code in that method is then executed. If an event-hander method has not been associated with the button, nothing happens.

2.

Why is it a good idea to write and test the code for laying out a window’s components before you add the methods that perform computations in response to events? Solution: It is a good idea to develop and test code for laying out a window’s components, to establish that the look and feel of the GUI meet user requirements. This can be complex code, and testing code for event handling at the same time can add unnecessary complexity to this step. Once you know that the layout code is correct, you can focus on developing and testing just the event-handling code. Divide and conquer!

EXERCISE 9.5 1.

Explain why you would not use a text field to perform input and output of numbers. Solution: If you used a text field to perform numeric input and output, you would have to convert the data from text to numbers after input and from numbers to text before output. The use of numeric fields eliminates these conversion steps, and, in the case of floating-point numbers, also allows you to specify the precision of the values displayed.

2.

Write a line of code that adds a FloatField to a window, at position (1, 1) in the grid, with an initial value of 0.0, a width of 15, and a precision of 2. Solution:

addFloatField(value = 0.0, row = 1, column = 1, width = 15,

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

104


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

precision = 2) 3.

What happens when you enter a number with a decimal point into an IntegerField? Solution: Python raises an exception when you enter a number with a decimal point into a FloatField. The error will occur when you run the getNumber method.

4.

When would you make a data field read-only, and how would you do this? Solution: You would make a data field read-only when it is only for output. You set the field’s state attribute to "readonly".

EXERCISE 9.6 1.

What is meant by the state of an object, and how does the programmer access and manipulate it? Solution: The state of an object is the values of all its attributes, which are contained in its instance variables, at any given time. The programmer accesses an object’s state in two ways. First, from within the object’s class definition, the programmer uses the prefix self with an instance variable to access or modify the value of that variable. Second, outside of the object’s class definition, or even also within it, the programmer can indirectly access the object’s state by running methods on that object that directly or indirectly access the state.

2.

Explain the differences between instance variables and temporary variables. Focus on their visibility in a class definition, and on their roles in managing data for an object of that class. Solution: An instance variable is visible to any method defined within the same class. A temporary variable is visible only within the method in which it is introduced. The purpose of a temporary variable is to provide temporary working storage for a single execution of a method. The purpose of an instance variable is to provide storage that tracks part of the state of an object during its entire lifetime.

3.

Explain the purpose of the variable self in a Python class definition. Solution: The variable self in a Python class definition is used to prefix the name of an instance variable or the name of a method in a method call in that class.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

105


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

REVIEW QUESTIONS ANSWERS 31. In contrast to a terminal-based program, a GUI-based program m. completely controls the order in which the user enters inputs n.

can allow the user to enter inputs in any order

o.

permits just text-based inputs

p.

permits just text-based outputs

Answer: b Feedback: kk. Incorrect. This is just one possible ordering. ll. Correct. All the input fields are available simultaneously. mm. Incorrect. Inputs can be mouse clicks. nn. Incorrect. Outputs can be images. 32. The main window class in a GUI-based program is a subclass of m. TextArea n.

EasyFrame

o.

Window

p.

Menu

Answer: b Feedback: gg. Incorrect. This class defines a multiline text box. hh. Correct. This class is the parent class of a GUI application window. ii. Incorrect. This is not the name of a window class in Python. jj. Incorrect This class defines the behavior of drop-down menus. 33. The attribute used to attach an event-handling method to a button is named m. row n.

column

o.

command

p.

text

Answer: c

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

106


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

Feedback: gg. Incorrect. This value of a row in the window’s grid. hh. Incorrect. This value of a row in the window’s grid. ii. Correct. An object is an instance of a class. jj. Incorrect. This value of a label in a window component.

34. GUIs represent color values using a.

RGB triples of integers

b.

hex strings

c.

the names of the colors

d.

instances of the class Color

Answer: b Feedback: gg. Incorrect. Not in Python. hh. Correct. Hex strings have the form "0xRRGGBB". ii.

Incorrect. Only for commonly used colors, but not generally.

jj. Incorrect. Not in Python.

35. Multiline text is displayed in a a.

text field

b.

text area

c.

label

d.

title bar of a window

Answer: b Feedback: e.

Incorrect. A text field contains a single line of text.

f.

Correct. Text areas contain multiple lines of text in a single chunk.

g.

Incorrect. A label contains a single line of text.

h.

Incorrect. A title bar contains a single line of text.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

107


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

36. The window component that allows a user to move the text visible beneath a TextArea widget is a m. list box n.

label

o.

scroll bar

p.

button

Answer: c Feedback: gg. Incorrect. A list box displayed multiple items of text in a list. hh. Incorrect. A label displays a single line of text. ii.

Correct. A scroll bar allows the user to navigate the visible area horizontally or vertically.

jj. Incorrect. A button displays a single line of text. 37. The sticky attribute a.

controls the alignment of a window component in its grid cell

b.

makes it difficult for a window component to be moved

c.

connects window components to each other

d.

automatically places the mouse pointer on a window component

Answer: a Feedback: a.

Correct. This attribute aligns a window object according to N, S, E, and W directions.

b.

Incorrect. Window objects are already fixed in grid cells.

c.

Incorrect. Window objects are organized in the window’s grid.

d.

Incorrect. The mouse point is under user control

38. A window component that supports selecting one option only is the e.

check button

f.

radio button

g.

text field

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

108


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

h.

text area

Answer: b Feedback: e.

Incorrect. Multiple check boxes can be selected.

f.

Correct. Only a single radio button can be selected.

g.

Incorrect. Text fields have no options.

h.

Incorrect. Text areas have no options.

39. A rectangular subarea with its own grid for organizing widgets is a e.

canvas

f.

panel

g.

list box

h.

combo box

Answer: b Feedback: e.

Incorrect. A canvas is just a two-dimensional drawing area.

f.

Correct. A panel is a two-dimensional area with a grid for holding widgets.

g.

Incorrect. A list box holds lines of text in a list.

h.

Incorrect. A combo box is a drop-down list of items.

40. The rows and columns in a grid layout are numbered starting from e.

(0, 0)

f.

(1, 1)

g.

(1, 0)

h.

(0, 1)

Answer: a Feedback: e.

Correct. This is the position in the upper-left corner of the grid.

f.

Incorrect. This is the second row and second column.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

109


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

g.

Incorrect. This is the second row and first column.

h.

Incorrect. This is the first row and second column.

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site 68. Write a GUI-based program in the file taxformwithgui.py that implements the tax calculator program shown in Figure 9-2. (LO: 9.2, 9.3, 9.4, 9.5) Solution: See taxformwithgui.py posted on the Instructor Companion Site

69. Write a GUI-based program in the file bouncywithgui.py that implements the bouncy program discussed in program in Programming Project 4 of Chapter 3. (LO: 9.2, 9.3, 9.4, 9.5) Solution: See bouncywithgui.py posted on the Instructor Companion Site

70. Write a GUI-based program in the file temperatureconverter.py that allows the user to convert temperature values between degrees Fahrenheit and degrees Celsius. The interface should have labeled entry fields for these two values. These components should be arranged in a grid where the labels occupy the first row and the corresponding fields occupy the second row. At start-up, the Fahrenheit field should contain 32.0, and the Celsius field should contain 0.0. The third row in the window contains two command buttons, labeled >>>> and <<<<. When the user presses the first button, the program should use the data in the Fahrenheit field to compute the Celsius value, which should then be output to the Celsius field. The second button should perform the inverse function. (LO: 9.2, 9.3, 9.4, 9.5) Solution: See temperatureconverter.py posted on the Instructor Companion Site

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

110


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

71. Modify the temperature conversion program in the file temperatureconverterwithkey.py so that it responds to the user’s press of the return or enter key. If the user presses this key when the insertion point is in a given field, the action which uses that field for input is triggered. (LO: 9.2, 9.3, 9.4, 9.5, 9.6) Solution: See temperatureconverterwithkey.py posted on the Instructor Companion Site

72. Write a GUI-based program in the file guesswithgui.py that plays a guess-the-number game in which the roles of the computer and the user are the reverse of what they are in the Case Study of this chapter. In this version of the game, the computer guesses a number between 1 and 100 and the user provides the responses. The window should display the computer’s guesses with a label. The user enters a hint in response, by selecting one of a set of command buttons labeled Too small, Too large, and Correct. When the game is over, you should disable these buttons and wait for the user to click New game, as before. (LO: 9.2, 9.3, 9.4, 9.5, 9.6, 9.7) Solution: See guesswithgui.py posted on the Instructor Companion Site

73. Add radio button options for filing status to the tax calculator program of Project 1 (in the file taxformwithgui.py). The user selects one of these options to determine the tax rate. The Single option’s rate is 20%. The Married option is 15%. The Divorced option is 10%. The default option is Single. (LO: 9.7) Solution: See taxformwithgui.py posted on the Instructor Companion Site

74. The TidBit Computer Store (Chapter 3, Programming Exercise 10) has a credit plan for computer purchases. Inputs are the annual interest rate and the purchase price. Monthly payments are 5% of the listed purchase price, minus the down payment, which must be 10% of the purchase price. Write a GUI-based program in the file tidbitwithgui.py that displays labeled fields for the inputs and a text area for the output. The program should display a table, with appropriate headers, of a payment schedule for the lifetime of the loan. Each row of the table should contain the following items: • The month number (beginning with 1)

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

111


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

• The current total balance owed • The interest owed for that month • The amount of principal owed for that month • The payment for that month • The balance remaining after payment The amount of interest for a month is equal to balance * rate / 12. The amount of principal for a month is equal to the monthly payment minus the interest owed. Your program should include separate classes for the model and the view. The model should include a method that expects the two inputs as arguments and returns a formatted string for output by the GUI. (LO: 9.2, 9.3, 9.4, 9.5, 9.6, 9.7) Solution: See tidbitwithgui.py posted on the Instructor Companion Site

75. Write a GUI-based program in the file texteditor.py that allows the user to open, edit, and save text files. The GUI should include a labeled entry field for the filename and a multiline text widget for the text of the file. The user should be able to scroll through the text by manipulating a vertical scrollbar. Include command buttons labeled Open, Save, and New that allow the user to open, save, and create new files. The New command should then clear the text widget and the entry widget. (LO: 9.2, 9.3, 9.4, 9.6, 9.7) Solution: See texteditor.py posted on the Instructor Companion Site

76. Write a GUI-based program in the file imagebrowser.py that implements an image browser for your computer’s file system. The look, feel, and program logic should be like those of the simple text file bowser developed in this chapter. The file dialog should filter for GIF image files and create and open a

PhotoImage when a file is accessed. (LO: 9.2, 9.3, 9.4, 9.6, 9.7) Solution: See imagebrowser.py posted on the Instructor Companion Site

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

112


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

DEBUGGING EXERCISE SOLUTION Jack is responsible for designing and laying out a GUI for the game of chess. A chessboard is an 8 by 8 grid of squares of alternating colors, where no two adjacent squares have the same color. A prototype of the desired interface is shown on the left in Figure 9.23, along with the result of Jack’s design effort thus far on the right. Obviously, there is an error somewhere in Jack’s code. Describe this error and suggest a remedy. Here is Jack’s code (in the file chessboard.py):

""" File: chessboard.py Displays an 8 by 8 grid of black and white squares of a chessboard. """

from breezypythongui import EasyFrame

class Chessboard(EasyFrame):

def __init__(self): """Sets up the window and the panels.""" EasyFrame.__init__(self, title = "Chess", width = 200, height = 100) color = "white" for row in range(8):

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

113


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

for column in range(8): if color == "black": color = "white" else: color = "black" self.addPanel(row = row, column = column, background = color)

def main(): """Instantiate and pop up the window.""" Chessboard().mainloop()

if __name__ == "__main__": main() Solution The error is that some adjacent squares (in the same columns) have the same colors; instead, the colors should alternate across columns and down rows. Jack gets the colors of the columns to alternate with the if-else statement within the nested for loop. But when control returns to the outer for loop, the current color is the color of the last square on the previous row, which then is changed to the opposite color when the nested loop is entered again. Thus, the color of the leftmost square is the same on each pass through the outer loop.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

114


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 9, Graphical User Interfaces

To remedy the problem, Jack should insert an if-else statement to switch the color between the header of the outer loop and the header of the nested loop. This will guarantee that the color of the leftmost square on each row will be the opposite of the color of the rightmost square on the previous row. Here is the corrected code:

""" File: chessboard.py Displays an 8 by 8 grid of black and white squares of a chessboard. """

from breezypythongui import EasyFrame

class Chessboard(EasyFrame):

def __init__(self): """Sets up the window and the panels.""" EasyFrame.__init__(self, title = "Chess", width = 200, height = 200) color = "white" for row in range(8): if color == "black":

# Alternate color for new row

color = "white" else: color = "black" for column in range(8): if color == "black": color = "white"

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

115


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

else: color = "black" self.addPanel(row = row, column = column, background = color)

def main(): """Instantiate and pop up the window.""" Chessboard().mainloop()

if __name__ == "__main__": main()

Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 10, DESIGN WITH CLASSES

TABLE OF CONTENTS Exercise Solutions ................................................................................................................................... 117 Exercise 10.1 ......................................................................................................................................... 117 Exercise 10.2 ......................................................................................................................................... 118 Exercise 10.3 ......................................................................................................................................... 119 Exercise 10.4 ......................................................................................................................................... 120 Review Questions Answers..................................................................................................................... 121 Programming Exercises Solutions ......................................................................................................... 125 Debugging Exercise Solution.................................................................................................................. 128

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

116


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

EXERCISE SOLUTIONS EXERCISE 10.1 37. What are instance variables, and what role does the name self play in the context of a class definition? Solution: An instance variable is an area of storage that is owned by a particular object or instance of a class. The variable self refers to an instance of a class within the context of that class’s definition, and it is used to pick out the instance variables and method calls for that particular object. 38. Explain what a constructor does. Solution: A constructor is a method that is run automatically when a programmer creates an instance of a class. The constructor usually initializes that object’s instance variables. 39. Explain what the __str__ method does and why it is a useful method to include in a class. Solution: The __str__ method returns the string representation of an object. Python’s print function automatically uses this method. It is also useful for debugging, for providing a quick view of the state of an object. 40. The Student class has no mutator method that allows a user to change a student’s name. Define a method setName that allows a user to change a student’s name. Solution:

def setName(self, newName): self.name = newName 41. The method getAge expects no arguments and returns the value of an instance variable named self.age. Write the code for the definition of this method. Solution:

def getAge(self): return self.age 42. How is the lifetime of an object determined? What happens to an object when it dies? Solution: The lifetime of an object extends from its instantiation to the point at which no references to it from the program that created it exist. The garbage collector recycles the memory for an object when it dies.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

117


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

EXERCISE 10.2 6.

Although the use of a PIN to identify a person’s bank account is simple, it’s not very realistic. Real banks typically assign a unique 12-digit number to each account and use this as well as the customer’s PIN during a login at an ATM. Suggest how to rework the banking system discussed in this section to use this information. Solution: A 12-digit ID number is added as a variable to an account. This number is randomly generated and unique within the bank. It is used with the PIN as the key in the dictionary to access the account. User inputs at an ATM are now an ID number and a PIN.

7.

What is a class variable? When should the programmer define a class variable rather than an instance variable? Solution: A class variable is a single area of storage common to all instances of a class. It should be used instead of an instance variable when there is an attribute with a value that all instances have in common.

8.

Describe how the arithmetic operators can be overloaded to work with a new class of numbers. Solution: Each operator corresponds to a standard method. The programmer defines the method in her class, and the class’s users can then use the operator.

9.

Define a method for the Bank class that returns the total assets in the bank (the sum of all account balances). Solution:

def getTotalAssets(self): totalAssets = 0 for account in self.accounts.values(): totalAssets += account.getBalance() 10. Describe the benefits of pickling objects for file storage. Solution: Pickling objects for file storage allows a data model to be shared with other applications or saved when a system is shut down. Pickling allows a programmer to load or save objects independently of their internal structure. 11. Why would you use a try-except statement in a program?

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

118


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

Solution: The try-except statement allows a program to catch and recover from errors raised by the interpreter. Including this statement allows a program to continue execution even when unanticipated conditions occur. This statement can also be used to terminate some loops conveniently. 12. Two playing cards can be compared by rank. For example, an ace is less than a 2. When c1 and c2 are cards, c1.rank < c2.rank expresses this relationship. Explain how a method could be added to the Card class to simplify this expression to c1 < c2. Solution: The Card class could include the __eq__ and __lt__ methods that compare cards with respect to their rank.

EXERCISE 10.3 3.

Define a function gridSum that computes and returns the sum of the numbers in its grid argument. Solution:

def gridSum(grid): theSum = 0 for row in range(grid.getHeight()): for column in range(grid.getWidth()): theSum += grid[row][column] return theSum 4.

Define a function gridMax that returns the largest value in its grid argument. Solution:

def gridMax(grid): theMax = grid[0][0] for row in range(grid.getHeight()): for column in range(grid.getWidth()): if grid[row][column] > theMax: theMax = grid[row][column] return theMax 5.

Define a function diagonal that builds and returns a list containing the values that appear in the positions that form a diagonal in its grid argument, running from the upper left position to the lower right position. You may assume that the height and the width of the grid are the same. Solution:

def diagonal(grid): values = [] column = 0 for row in range(grid.getHeight()):

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

119


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

values.append(grid[row][column]) column += 1 return values 6.

Define an __eq__ method for the Grid class. This method returns True if the two grids have the same dimensions and the same values at the corresponding positions. Don’t forget to test for identity and the same types of arguments first. Solution:

def __eq__(self, other): if self is other: return True if type(self) != type(other): return False if self.getHeight() != other.getHeight(): return False if self.getWidth() != other.getWidth(): return False for row in range(self.getHeight()): for column in range(self.getWidth()): if self[row][column] != other[row][column]: return False return True

EXERCISE 10.4 5.

What are the benefits of having class B extend or inherit from class A? Solution: If class B extends class A, then users of class B get all of class A’s methods for free by inheritance. Also, the implementer of class B gets all of class A’s variables for free. The real advantage lies in reuse of code.

6.

Describe what the __init__ method should do in a class that extends another class. Solution: The __init__ method of the subclass should first run the __init__ method of its parent class. Each __init__ method should be responsible for initializing the instance variables of the class within which it is defined.

7.

Class B extends class A. Class B defines an __str__ method that returns the string representation of its instance variables. Class B defines a single instance variable named age, which is an integer. Write the code to define the __str__ method for class B. This method should return the combined string information from both classes. Label the data for age with the string "Age: ". Solution:

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

120


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

def __str__(self): result = A.__str__(self) return result + "\nAge: " + str(self.age)

REVIEW QUESTIONS ANSWERS 41. An instance variable refers to a data value that q.

is owned by a particular instance of a class and no other

r.

is shared in common and can be accessed by all instances of a given class

s.

is visible just within the method where it is introduced

t.

cannot be modified outside the scope of the class where it is defined

Answer: a Feedback: oo. Correct. This is the proper meaning and purpose of an instance variable. pp. Incorrect. This is a class variable. qq. Incorrect. This is a temporary variable. rr. Incorrect. Not true in Python. 42. The name used to refer to the current instance of a class within the class definition is q.

this

r.

other

s.

self

t.

super

Answer: c Feedback: kk. Incorrect. In Java and C++. ll. Incorrect. other is used for some other object. mm. Correct. self refers to this particular object itself. nn. Incorrect super is used to refer to the part of an instance that is defined in a parent class. 43. The purpose of the __init__ method in a class definition is to q.

build and return a string representation of the instance variables

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

121


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

r.

set the instance variables to initial values

s.

return storage for variables to the PVM

t.

display an object’s print representation in IDLE

Answer: b Feedback: kk. Incorrect. This is the __str__ method. ll. Correct. The instance variables are initialized to their values here. mm. Incorrect. This is automatic. nn. Incorrect. This is the __repr__ method.

44. A method definition a.

can have zero or more parameter names

b.

always must have at least one parameter name, called self

c.

must have at least two parameter names

d.

must include a return statement

Answer: b Feedback: kk. Incorrect. self is a required parameter. Correct. self is a required parameter.

ll. mm.

Incorrect. Some methods can take no arguments when called.

nn. Incorrect. return statement is optional.

45. The scope of an instance variable is a.

the statements in the body of the method where it is introduced

b.

the entire class in which it is introduced, as well as any module in which an object that owns the variable is referenced

c.

the entire module where it is introduced

d.

undefined

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

122


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

Answer: b Feedback: i.

Incorrect. This is a temporary variable.

j.

Correct. An instance variable is accessed using self or a reference to an object that owns it.

k.

Incorrect. This is a module variable.

l.

Incorrect. The scope of any variable is always defined.

46. An object’s lifetime ends q.

several hours after it is created

r.

when it can no longer be referenced anywhere in a program

s.

when its data storage is recycled by the garbage collector

t.

not ever

Answer: b Feedback: kk. Incorrect. This may or may not be true. ll.

Correct. At this point, the object has passed on.

mm.

Incorrect. Garbage collection provides a post-mortem burial for an object.

nn. Incorrect. This may or may not be true. 47. A class variable is used for data that a.

all instances of a class have in common

b.

each instance owns separately

c.

belong to a module

d.

are strings only

Answer: a Feedback: e.

Correct. The value of a class variable is unique and the same for all instances of that class.

f.

Incorrect. This would be an instance variable.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

123


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

g.

Incorrect. This would be a module variable.

h.

Incorrect. A class variable can refer to any type of data.

48. Class B is a subclass of class A. The __init__ methods in both classes expect no arguments. The call of class A’s __init__ method in class B is i.

A.__init__()

j.

A.__init__(self)

k.

__init__()

l.

__init__(self)

Answer: b Feedback: i.

Incorrect. self (the instance of B) must be included as an argument.

j.

Correct. self (the instance of B) is included as an argument.

k.

Incorrect. This is B’s __init__ method.

l.

Incorrect. This is B’s __init__ method.

49. The easiest way to save objects to permanent storage is to i.

convert them to strings and save this text to a text file

j.

pickle them using the pickle function dump

k.

use Python’s write method

l.

use a text file

Answer: b Feedback: i.

Incorrect. Converting an object to text is tedious, error-prone, and maintenance-heavy.

j.

Correct. This function does all the work of saving an object to a file.

k.

Incorrect. This method is used with text files.

l.

Incorrect. Converting an object to text is tedious, error-prone, and maintenance-heavy.

50. A polymorphic method

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

124


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

i.

has a single header but different bodies in different classes

j.

creates harmony in a software system

k.

has the same name as other methods but has a different number of parameters

l.

makes object-oriented software systems more complex than they need to be

Answer: a Feedback: i.

Correct. They have the same interface (header) but different implementations (body).

j.

Incorrect. This would be polyphonic.

k.

Incorrect. Method headers must be exactly the same.

l.

Incorrect. Polymorphism actually makes object-oriented systems simpler (for clients) than they would otherwise be, by keeping the number of method names to a minimum.

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on Cengage Instructor Center. 77. Add three methods to the Student class (in the file student.py) that compare two Student objects. One method should test for equality. A second method should test for less than. The third method should test for greater than or equal to. In each case, the method returns the result of the comparison of the two students’ names. Include a main function that tests all of the comparison operators. (LO: 10.2) Solution: See student.py posted on the Instructor Companion Site. 78. This exercise assumes that you have completed Programming Exercise 1. Place several Student objects containing different names into a list and shuffle it. Then run the sort method with this list and display all of the students’ information. (LO: 10.1, 10.2) Solution: See student.py posted on the Instructor Companion Site

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

125


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

79. The str method of the Bank class (in the file bank.py) returns a string containing the accounts in random order. Design and implement a change that causes the accounts to be placed in the string by order of name. (Hint: You will also have to define some methods in the SavingsAccount class, in the file savingsaccount.py.) (LO: 10.1, 10.2) Solution: See bank.py and savingsaccount.py posted on the Instructor Companion Site. 80. The ATM program allows a user an indefinite number of attempts to log in. Fix the program (in the file atm.py) so that it displays a popup message that the police will be called after a user has had three successive failures. The program should also disable the login button when this happens. (LO: 10.1) Solution: See atm.py posted on the Instructor Companion Site. 81. The Doctor program described in Chapter 5 combines the data model of a doctor and the operations for handling user interaction. Restructure this program according to the model/view pattern so that these areas of responsibility are assigned to separate sets of classes. The program (in the file doctor.py) should include a Doctor class with an interface that allows one to obtain a greeting, a signoff message, and a reply to a patient’s string. The rest of the program, in a separate main program module, handles the user’s interactions with the Doctor object. You may develop either a terminal-based user interface (also in doctor.py) or a GUI (in doctorgui.py). (LO: 10.1, 10.2) Solution: See doctor.py and doctorgui.py posted on the Instructor Companion Site. 82. The play method in the Player class of the craps game plays an entire game without interaction with the user. Revise the Player class (in the file craps.py) so that its user can make individual rolls of the dice and view the results after each roll. The Player class no longer accumulates a list of rolls but saves the string representation of each roll after it is made. Add new methods rollDice, getRollsCount,

isWinner, and isLoser to the Player class. The last three methods allow the user to obtain the number of rolls and to determine whether there is a winner or a loser. The last two methods are associated with new Boolean instance variables. Two other instance variables track the number of rolls and the string representation of the most recent roll. Another instance variable tracks whether or not the first roll has

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

126


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

occurred. At instantiation, the roll, rollsCount, atStartup, winner, and loser variables are set to their appropriate initial values. All game logic is now in the rollDice method. This method rolls the dice once, updates the state of the Player object, and returns a tuple of the values of the dice for that roll. Include in the module the playOneGame and playManyGames functions, suitably updated for the new interface to the Player class. (LO: 10.1, 10.2) Solution: See craps.py and die.py posted on the Instructor Companion Site. 83. Convert the DiceDemo program discussed in this chapter to a completed craps game application (in the file crapsgui.py), using the Player data model class you developed in Programming Exercise 6. A screen shot of a possible window is shown in Figure 10-7. (LO: 10.1, 10.2)) Solution: See craps.py, die.py, and crapsgui.py posted on the Instructor Companion Site. 84. In many card games, cards are either face up or face down. Add a new instance variable named faceup to the Card class (in the file cards.py) to track this attribute of a card. Its default value is False. Then add a turn method to turn the card over. This method resets the faceup variable to its logical negation. (LO: 10.1, 10.2) Solution: See cards.py posted on the Instructor Companion Site. 85. Computer card games are more fun if you can see the images of the cards in a window, as shown in the screen shot in Figure 10-8. Assume that the 52 images for a deck of cards are in a DECK folder, with the file naming scheme <rank number><suit letter>.gif. Thus, for example, the image for the Ace of Hearts is in a file named 1h.gif, and the image for the King of Spades is in a file named 13s.gif. Furthermore, there is an image file named b.gif for the backside image of all the cards. This will be the card’s image if its

faceup variable is False. Using the DiceDemo program as a role model, write a GUI program (in the files cardsgui.py and cards.py) that allows you to deal and view cards from a deck. Be sure to define a helper method that takes a Card object as an argument and returns its associated image, and remember to turn the cards as you deal them. (LO: 10.1, 10.2) Solution: See cards.py and cardsgui.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

127


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

86. Geometric shapes can be modeled as classes. Develop classes for line segments, circles, and rectangles. Each shape object should contain a reference to a Turtle object and a color that allow the shape to be drawn in a Turtle graphics window (see Chapter 8 for details). Factor the code for these features (instance variables and methods) into an abstract Shape class (in the file shapes.py). The Circle,

Rectangle, and Line classes are all subclasses of Shape. These subclasses include other information about the specific types of shapes, such as a radius or a corner point and a draw method. Write a script (in the file testshapes.py) that uses several instances of the different shape classes to draw a house and a stick figure. (LO: 10.1, 10.2, 10.4) Solution: See shapes.py and testshapes.py posted on the Instructor Companion Site.

DEBUGGING EXERCISE SOLUTION Jack is testing the Student class developed earlier in this chapter. He creates an instance of this class with 0 scores and receives an error message when he attempts to view the average score:

>>> s = Student("Jack", 0) >>> print(s) Name: Jack Scores: >>> s.getAverageScoreScore() Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> s.getAverageScore() File "/Users/ken/pythonfiles/student.py", line 42, in getAverageScoreScore

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

128


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 10, Design with Classes

return sum(self.scores) / len(self.scores) ZeroDivisionError: division by zero Explain the error detected during this test and describe a way to prevent it from happening. Solution: The error is an attempt to divide by zero, which occurs in the expression sum(self.scores) /

len(self.scores) because the length of the scores list is 0. To prevent this error from happening, the __init__ method can put a precondition on the number of scores, which must be greater than zero, and raise an exception if the programmer tries to pass a 0 for this value when the Student object is instantiated. Here is the code for the revised __init__ method:

def __init__(self, name, number): """All scores are initially 0. Precondition: number > 0.""" if number <= 0: raise RuntimeError("number must be > 0") self.name = name self.scores = [] for count in range(number): self.scores.append(0)

Solution and Answer Guide © 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

129


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 11, Data Analysis and Visualization

LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 11, DATA ANALYSIS AND VISUALIZATION

TABLE OF CONTENTS Exercise Solutions ................................................................................................................................... 130 Exercise 11.1 ......................................................................................................................................... 130 Exercise 11.2 ......................................................................................................................................... 131 Exercise 11.3 ......................................................................................................................................... 131 Review Questions Answers..................................................................................................................... 132 Programming Exercises Solutions ......................................................................................................... 136

EXERCISE SOLUTIONS EXERCISE 11.1 43. The variance of a data set is defined to be the mean of the squares of the numbers in a list minus the square of the mean of those numbers. Define a Python function that computes and returns this value (you may use the mean function defined earlier). Solution: def variance(lyst): return mean(list(map(lambda x: x ** 2, lyst))) - mean(lyst) 44. The percentile of a value is the part of its data set into which it falls (or rises). For example, to rise into the 90th percentile means that at least 90% of the other values lie below the given value (assuming they are in descending order). Describe a strategy for computing the percentile of a given value in a list of values. Solution: To compute a given value’s percentile, one would sort the list of values in descending order, determine the value’s position in the sorted list, and divide the number of positions below the value’s position by the length of the list. This fraction could then be multiplied by 100 to give an integer result. 45. Why do most of the data analysis functions have a precondition? Solution: It is not meaningful to compute a mean, median, mode, or standard deviation of an empty data set.

46. Explain the difference between the median and the mean of a data set. Explain why you might select one function rather than the other. Solution:

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

130


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 11, Data Analysis and Visualization

The mean of a data set is the average value. The median of a data set is the value that would appear at its midpoint if the data were sorted. A data set with a predominance of small or large values can skew the mean, so the median might indicate a more normal value.

EXERCISE 11.2 13. Describe the difference between a scatter plot and a line plot. Solution: A scatter plot displays data values as a set of points or dots, with the value on the y-axis and its position or label on the x-axis. A line plot is a scatter plot with the points or dot connected by line segments. 14. Describe the difference between a bar chart and a histogram. Solution: A bar chart displays each datum’s magnitude as a bar of a certain length. A histogram displays a datum’s frequency (the number of its instances) in a data set as a bar of a certain length. 15. Describe how one would plot several data sets in the same line plot. Solution: Each data set would be passed to the plot function. Ideally, the color for each plot would be different, and the legend would also help to distinguish them. 16. When is it appropriate to visualize a data set using a pie chart? Solution: A pie chart is most useful for visualizing the relative percentages of pieces of a single data set. 17. Jill wants to create a histogram of a concordance, which represents the frequencies of words in a text file. Should she align the histogram vertically or horizontally, and why? Solution: The words in a piece of text can be of varying lengths, and some can be relatively long (10 characters or more). Moreover, there might be many unique words in this data set. Therefore, it would be prudent to display the words along the y-axis and their frequencies along the x-axis of a horizontal histogram.

EXERCISE 11.3 7.

Explain the difference between a data frame and a series. Solution: A data frame represents a data set as a multidimensional table of values. A series represents a data set as a linear sequence of values.

8.

Give two reasons why a data set might have to be cleaned, and describe the techniques used to clean it.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

131


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 11, Data Analysis and Visualization

Solution: A data set might contain null values, which represent values absent from rows. Or a value in a data set might seem obviously incorrect in some way. In very large data sets, rows with null or incorrect values can be removed without much impact on analysis. In smaller data sets, these values can be replaced with values that represent reasonable default values, such as the mean or median of the values in their row or column. 9.

What is a CSV file, and how does it map data to a data frame? A CSV file is a text file which contains comma-separated values. Each line in the file represents a row in a data set, and the columns are indicated by the commas separating the values on a line. The first line in a CSV file typically includes the headings of the columns in the data set. When loaded into a data frame, the first line of the file is used for the headings of the frame’s columns, and each of the other lines becomes a row in the frame.

REVIEW QUESTIONS ANSWERS 51. The mean of a given set of numbers refers to the u.

average of the numbers.

v.

number that lies at the midpoint when the numbers are sorted.

w. number that appears most frequently. x.

average distance of the numbers from the mean.

Answer: a Feedback: ss. Correct. The mean is the average. tt. Incorrect. This is the median. uu. Incorrect. This is the mode. vv. Incorrect. This is the standard deviation. 52. The median of a given set of numbers refers to the a.

average of the numbers.

b.

number that lies at the midpoint when the numbers are sorted.

c.

number that appears most frequently.

d.

average distance of the numbers from the mean.

Answer: b Feedback: a.

Incorrect. The mean is the average.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

132


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 11, Data Analysis and Visualization

b. c. d.

Correct. This is the median. Incorrect. This is the mode. Incorrect. This is the standard deviation.

53. The mode of a given set of numbers refers to the a.

average of the numbers.

b.

number that lies at the midpoint when the numbers are sorted.

c.

number that appears most frequently.

d.

average distance of the numbers from the mean.

Answer: c Feedback: a. b. c. d.

Incorrect. The mean is the average. Incorrect. This is the median. Correct. This is the mode. Incorrect. This is the standard deviation.

54. The standard deviation of a given set of numbers refers to the a.

average of the numbers.

b.

number that lies at the midpoint when the numbers are sorted.

c.

number that appears most frequently.

d.

average distance of the numbers from the mean.

Answer: d Feedback: a. b. c. d.

Incorrect. The mean is the average. Incorrect. This is the median. Incorrect. This is the mode. Correct. This is the standard deviation.

55. A scatter plot is useful for visualizing a.

clusters of data.

b.

increasing or decreasing trends of data.

c.

values plotted along a continuous range.

d.

relative percentages of groups of data in a whole.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

133


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 11, Data Analysis and Visualization

Answer: a Feedback: m. Correct. This is a scatter plot. n.

Incorrect. This is a line plot.

o.

Incorrect. This is a line plot.

p.

Incorrect. This is a pie chart.

56. A pie chart is useful for visualizing a.

clusters of data.

b.

increasing or decreasing trends of data.

c.

values plotted along a continuous range.

d.

relative percentages of groups of data in a whole.

Answer: d Feedback: a.

Incorrect. This is a scatter plot.

b.

Incorrect. This is a line plot.

c.

Incorrect. This is a line plot.

d.

Correct. This is a pie chart.

57. A histogram is useful for visualizing a.

clusters of data.

b.

increasing or decreasing trends of data.

c.

relative frequencies of data.

d. relative percentages of groups of data in a whole. Answer: c Feedback: a.

Incorrect. This is a scatter plot.

b.

Incorrect. This is a line plot.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

134


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 11, Data Analysis and Visualization

c.

Correct. This is a histogram.

d.

Incorrect. This is a pie chart.

58. A data frame is a structure that represents a.

rows and columns in a multidimensional table of data.

b.

a single row or column of data.

c.

the boundary of a set of data in a graphical display.

d.

a snapshot of data in a list.

Answer: a Feedback: i.

Correct. A data frame consists of rows and columns of data.

j.

Incorrect. This is a series.

k.

Incorrect. These are the axes.

l.

Incorrect. This is a sublist.

59. A series is a structure that represents a.

rows and columns in a multidimensional table of data.

b.

a single row or column of data.

c.

the boundary of a set of data in a graphical display.

d.

a snapshot of data in a list.

Answer: b Feedback: a.

Incorrect. A data frame consists of rows and columns of data.

b.

Correct. This is a series.

c.

Incorrect. These are the axes.

d.

Incorrect. This is a sublist.

60. The term CSV in the expression CSV file stands for m. comma-separated values. n.

comma-spliced values.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

135


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 11, Data Analysis and Visualization

o.

comma-stored version.

p.

a popular pharmacy.

Answer: b Feedback: m. Correct. Commas separate the values on each line of text in the file. n.

Incorrect. Values aren’t spliced with commas in the file.

o.

Incorrect. Wrong answer.

p.

Incorrect. Wrong answer—that’s CVS.

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 87. Complete the implementation of the Student class from the Analyzing Student Test Scores case study. Include a short tester program in a file named studenttest.py that exercises the new methods. (LO: 11.1) Solution: See student.py and studenttest.pys posted on the Instructor Companion Site. 88. This exercise assumes that you have completed Programming Exercise 1. Complete the implementation

StudentView class from the Analyzing Student Test Scores case study. (LO: 11.1) Solution: See studentview.py posted on the Instructor Companion Site 89. Add a command button named Plot to the user interface for Analyzing Student Test Scores case study. When the user selects this button, the program displays a line plot of the student’s test scores. (LO: 11.2) Solution: See studentview.py posted on the Instructor Companion Site. 90. Write a program in the file histogram.py that displays the histogram depicted in Figure 11.7. (LO: 11.2) Solution: See histogram.py posted on the Instructor Companion Site. 91. Visit the website of the U.S. Bureau of Labor Statistics at https://www.bls.gov/data/home.htm and download the data for the average price of bread, as you did earlier in this chapter (there will be data for

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

136


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 11, Data Analysis and Visualization

more recent years added since these words were written). Write a program in a file named breadprices.py to the data set and display it as you did earlier, and then include code to display a line plot of the average price for each year in the table. (LO: 11.1, 11.2, 11.3) Solution: See breadprices.py posted on the Instructor Companion Site.

92. The columns labeled FG, 3PT, and FT of the data set in the Analyzing Basketball Statistics case study do not show a single integer value but instead show the format <makes-attempts>, which is not suitable for the kind of data analysis performed on the other columns. For example, analysts would like to view the mean of free throws attempted as well as mean of the free throw percentage. You can correct this problem with a cleaning step that, for each such column, 

removes it from the data frame

creates two new columns from this series, where the first column includes the numbers of makes and the second column includes the number of attempts

inserts the new pairs of columns into the data frame at the appropriate positions with the appropriate labels (using, for example, FGM and FGA)

Define a function named cleanStats in the file hoopstatsapp.py. This function expects a data frame as an argument and returns the frame cleaned according to the steps listed previously. You should call this function after the frame is loaded from the CSV file and before it is passed to the HoopStatsView

constructor. (LO: 11.2, 11.3) Solution: See hoopstatsapp.py posted on the Instructor Companion Site. 93. This exercise assumes that you have completed Programming Exercise 6. Add radio

buttons for the remaining columns of data in the data set to the program of the Analyzing Basketball Statistics Case study. (LO: 11.3) Solution: See hoopstatsview.py posted on the Instructor Companion Site. 94. Add a line plot feature to the program of the Analyzing Basketball Statistics case study. When the user selects a radio button, the data for a column are analyzed and the program displays the results as before, but

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

137


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

the program also pops up a line plot of the selected column of data. The line plot’s y-axis should be labeled with the name of the column heading. (LO: 11.2, 11.3) Solution: See hoopstatsview.py posted on the Instructor Companion Site.

Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 12, MULTITHREADING , NETWORKS, AND CLIENT-SERVER PROGRAMMING

TABLE OF CONTENTS Exercise Solutions ................................................................................................................................... 138 Exercise 12.1 ......................................................................................................................................... 138 Exercise 12.2 ......................................................................................................................................... 139 Exercise 12.3 ......................................................................................................................................... 141 Review Questions Answers..................................................................................................................... 142 Programming Exercises Solutions ......................................................................................................... 146 Debugging Exercise Solution........................................................................ Error! Bookmark not defined.

EXERCISE SOLUTIONS EXERCISE 12.1 47. Describe the purpose of a thread’s run method. Solution: The run method in a given thread is automatically called when the thread’s start method is called. The run method places the thread at the rear of a ready cue to wait for access to the CPU. The run method should include the code that the programmer intends to execute in that thread. When the thread gains access to the CPU, the code in its run method begins to execute or resumes execution at the point where the thread most recently had access to the CPU. 48. What is time slicing? Solution:

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

138


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

Time slicing is a means of giving multiple threads equal turns at execution in a single CPU. After executing its instructions for a small segment (slice) of time, a thread’s context is saved and it suspends execution and moves to the end of the ready queue. The thread at the front of the queue then gains access to the CPU, after its context is restored, to resume execution. 49. What is a synchronization problem? Solution: When multiple threads are executing concurrently, two or more threads may attempt to access the same data in shared memory. If none of the threads modify this memory, they may access it in any order. However, if at least one thread modifies memory, the other threads must wait until this thread finishes the operation. A synchronization problem occurs when the appropriate ordering of access is not enforced— some access to shared data may occur too soon, too late, or not at all.

50. What is the difference between a sleeping thread and a waiting thread. Solution: A sleeping thread has become inactive for a given segment of time (as the result of calling time.sleep when running), and it returns to the ready queue when this time expires. A waiting thread has become inactive as the result of calling the wait method on a given Condition object. A waiting thread returns to the ready queue as the result of being notified by the currently running thread. The latter thread does this either by calling notify on the Condition object (if the waiting thread is at the front of the Condition’s queue of waiting threads) or by calling notifyAll (which returns all the threads waiting on that Condition to the ready queue).

51. Give two real-world examples of the producer–consumer problem. Solution: Three golfers are waiting in line to obtain buckets of golf balls to hit at a driving range. The plastic buckets are stacked up on poles near the machine that dispenses the balls. A golfer must place an empty bucket under the dispenser before dropping a token into it to begin the dispensation process. That golfer must then remove the filled bucket before another bucket can be filled. Clearly, these steps in producing and consuming must be synchronized to avoid mishaps, such as golf balls spilling all over the ground.

EXERCISE 12.2 18. Give two real-world examples of the readers and writers problem. Solution: One example of the readers and writers problem is a multiuser chat room. Each user gets an update of the entire conversation by reading from a common database, while each user also gets to contribute to the conversation by sending an update. Another example is a medical records system where doctors and insurance companies can be concurrently reading from or writing to a patient’s record. 19. State two ways in which the readers and writers problem is different from the producer–consumer problem.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

139


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

Solution: Order (producer acts before consumer) is critical in the producer–consumer problem, but not in the readers and writers problem. Also, there can be many readers and writers, whereas there can only be one producer and one consumer. 20. Describe how you would make the Student class from Chapter 10 thread-safe for readers and writers. Solution: To make the Student class thread-safe, one could define a class called ThreadSafeStudent, using the decorator pattern. The new class would have the same interface as Student but would encase the Student object within a shared cell that provides the appropriate synchronization for the accessor and mutator methods. Then one could use objects of the new class in the same manner as objects of the Student class, but in multithreaded reader and writer situations. 21. Define a new class called PCSharedCell. This class provides an abstraction of a shared cell for the producer–consumer problem. The design pattern should be similar for the one presented for the shared cell for readers and writers, but it should use the mechanism specific to the producer–consumer situation. Solution:

import time, random from threading import Condition class PCSharedCell(object): """Shared data that sequences reading and writing.""" def __init__(self, data): """Can produce but not consume at startup.""" self.data = data self.writeable = True self.condition = Condition() def write(self, data, writerFunction): """Second caller must wait until someone has consumed the data before resetting it.""" self.condition.acquire() while not self.writeable: self.condition.wait() result = writerFunction(self.data) self.writeable = False self.condition.notify() self.condition.release() return result def read(self, readerFunction): """Caller must wait until someone has produced

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

140


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

the data before accessing it.""" self.condition.acquire() while self.writeable: self.condition.wait() result = readerFunction(self.data) self.writeable = True self.condition.notify() self.condition.release() return result

EXERCISE 12.3 10. Explain the roles that ports and IP addresses play in a client/server program. Solution: A port is a channel through which a server receives connections from clients. A server can serve many clients through a single port. An IP address uniquely identifies a server to clients or clients to a server on a network. 11. What is a local host, and how is it used to develop networked applications? Solution: A local host is an IP address of a server’s computer used when it is not connected to a network. This IP address can be used to develop a client/server application and test it before deploying it on a network. 12. Why is it a good idea for a server to create threads to handle clients’ requests? Solution: When a server creates a thread to handle a client’s request, the server is then free to listen for other client requests for service. This means that a new client will not have to wait until another client’s service has been completed. 13. Describe how a menu-driven command processor of the type developed for an ATM application in Chapter 10 could be run on a network. Solution: An ATM could run as a client application. At startup, the client sends the user’s name and password to the server. The server replies with a successful or unsuccessful login message. If the login is successful, the other ATM commands are enabled. When the user enters a command, a special string is sent to the server to request that service. The string includes a command and any required arguments. When the server receives such a string, it performs the transaction with the bank. The server also replies to the client with the results of the transaction. When the server starts up, it loads the bank’s data from a file, instantiates the bank, and listens for client requests. When a client connects, the server creates a client socket and starts a client handler thread with that socket and the bank object.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

141


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

14. The ATM application discussed in Chapter 10 has a single user. Will there be a synchronization problem if we deploy that application with threads for multiple users? Justify your answer. Solution: There will not be a synchronization problem for access to individual accounts as long as they are not joint accounts. If they were, then they would need a locking mechanism to ensure that an account is accessed by only one writer at a time. Because the Bank object uses a thread-safe dictionary to hold the accounts, the operations on the bank (as distinct from those on an individual account) are already synchronized. 15. The servers discussed in this section all contain infinite loops. Thus, the applications running them cannot do anything else while the server is waiting for a client’s request, and they cannot even gracefully be shut down. Suggest a way to restructure these applications so that the applications can do other things, including performing a graceful shutdown. Solution: A sever can be defined as a subclass of Thread and run as a separate thread from the main application. This will allow the main application to do other things while the server thread waits for client connections. The server class can also include a quit method. The main application can run this method to shut the server down. The quit method sets a Boolean instance variable to False. This variable is set to True when the thread is instantiated and can control the loop that listens for client connections.

REVIEW QUESTIONS ANSWERS 61. Multiple threads can run on the same desktop computer by means of y.

time-sharing

z.

multiprocessing

aa. distributed computing bb. multiple windows Answer: b Feedback: ww. Incorrect. Time-sharing allows multiple users to run programs simultaneously and remotely on the same CPU. xx. Correct. Multiprocessing allows a single user to run multiple programs simultaneously on a desktop computer. yy. Incorrect. Distributed computing runs programs on computers connected in a network. zz. Incorrect. Windows are user interface components of programs. 62. A Thread object moves to the ready queue when u.

its wait method is called

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

142


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

v.

its sleep method is called

w. its start method is called x.

its __init__ method is called

Answer: c Feedback: oo. Incorrect. wait makes a thread inactive until it is notified. pp. Incorrect. spleep makes a thread inactive for a given time interval. qq. Correct. start method makes a thread ready. rr. Incorrect __init__ initializes a thread’s instance variables. 63. The method that executes a thread’s code is called u.

the start method

v.

the run method

w. the execute method x.

the __init__ method

Answer: b Feedback: oo. Incorrect. start method makes a thread ready. pp. Correct. run executes a thread’s code. qq. Incorrect. execute is not a thread method. rr. Incorrect. __init__ initializes a thread’s instance variables.

64. A lock on a resource is provided by an instance of the a.

Thread class

b.

Condition class

c.

Lock class

d.

Vault class

Answer: b Feedback:

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

143


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

oo. Incorrect. Thread represents threads. pp. Correct. Condition represents a lock on a resource. qq. Incorrect. Lock is not a class. rr. Incorrect. Vault is not a class.

65. If multiple threads share data, they can have a.

total cooperation

b.

synchronization problems

c.

equal access to the data

d.

independent access to the data

Answer: b Feedback: q.

Incorrect. This is not guaranteed.

r.

Correct. Writers to shared data might not finish before readers access, and conversely.

s.

Incorrect. This is not guaranteed.

t.

Incorrect. This is not true by definition.

66. The object that uniquely identifies a host computer on a network is a(n) u.

port

v.

socket

w. IP address x.

thread

Answer: b Feedback: oo. Incorrect. A port allows several clients to access a server on a host computer. pp. Incorrect. A socket effects a connection between an individual client and a server. qq. Correct. An IP address uniquely identifies a host computer on a network.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

144


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

rr. Incorrect. A thread represents a process that can run concurrently with other processes. 67. The object that allows several clients to access a server on a host computer is a(n) a.

port

b.

socket

c.

IP address

d.

thread

Answer: a Feedback: a.

Incorrect. A port allows several clients to access a server on a host computer.

b.

Incorrect. A socket effects a connection between an individual client and a server.

c.

Correct. An IP address uniquely identifies a host computer on a network.

d.

Incorrect. A thread represents a process that can run concurrently with other processes.

68. The object that effects a connection between an individual client and a server is a(n) a.

port

b.

socket

c.

IP address

d.

thread

Answer: b Feedback: a.

Incorrect. A port allows several clients to access a server on a host computer.

b.

Correct. A socket effects a connection between an individual client and a server.

c.

Incrrect. An IP address uniquely identifies a host computer on a network.

d.

Incorrect. A thread represents a process that can run concurrently with other processes.

69. The data that are transmitted between client and server are q.

of any type

r.

strings

s.

bytes

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

145


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

t.

lists

Answer: c Feedback: q.

Incorrect. Data must be converted to a string and then to byes before being sent.

r.

Incorrect. A string must be converted to bytes before being sent and decoded after being received.

s.

Correct. Data must be converted to bytes before being sent and decoded after being received.

t.

Incorrect. Data must be converted to a string and then to byes before being sent.

70. The best way for a server to handle requests from multiple clients is to m. directly handle each client’s request n.

create a separate client-handler thread for each client

o.

refuse requests to connect after the first request

p.

handle the requests in random order

Answer: b Feedback: m. Incorrect. This makes clients wait for service when they need not. n.

Correct. This enforces first-come first-served fairness and makes no client wait for service.

o.

Incorrect. This defeats the idea of client/server, which is to have one resource serve many clients.

p.

Incorrect. This defeats the idea of first-come first served fairness.

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 95. Redo the producer/consumer program (in the file pc.py) so that it allows multiple consumers. Each consumer must be able to consume the same data before the producer produces more data. (LO: 12.1) Solution: See pc.py posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

146


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

96. Sometimes servers are down, so clients cannot connect to them. Python raises an exception of type

ConnectionRefusedError in a client program when a network connection is refused. Add code to the day/time client program (in the file timeclient.py) to catch and recover from this kind of exception. (LO: 12.3) Solution: See timeclient.py posted on the Instructor Companion Site 97. Modify the code in the day/time server application (in the file timeserver.py) so that the user on the server side can shut the server down. That user should be able to press the return or enter key at the terminal to do this. (LO: 12.3) Solution: See timeserver.py posted on the Instructor Companion Site. 98. Modify the doctor application discussed in this chapter so that it tracks clients by name and history. A

Doctor object has its own history list of a patient’s inputs for generating replies that refer to earlier conversations, as discussed in Chapter 5. A Doctor object (in the file doctor.py) is now associated with a patient’s name. The client application (in the file doctorclient.py) takes this name as input and sends it to the client handler (in the file doctorclienthandler.py) when the patient connects. The client handler checks for a pickled file with the patient’s name as its filename ("<patient name>.dat"). If that file exists, it will contain the patient’s history, and the client handler loads the file to create the Doctor object. Otherwise, the patient is visiting the doctor for the first time, so the client handler creates a brandnew Doctor object. When the client disconnects, the client handler pickles the Doctor object in a file with the patient’s name. (LO: 12.3) Solution: See doctor.py, doctorclient.py, and doctorclienthandler.py posted on the Instructor Companion Site. 99. Design, implement, and test a network application that maintains an online phone book. The data model for the phone book (in the file phonebook.py) is saved in a file on the server’s computer. A client (in the file phonebookclient.py) should be able to look up a person’s phone number or add a name and number to the phone book. The server (in the file phonebookserver.py) should handle multiple clients without delays.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

147


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

Unlike the doctor program, there should be just one phone book that all clients share. The server creates this object at start-up and passes it to the client handlers (in the file phonebookclienthandler.py). (LO: 12.1, 12.3) Solution: See phonebook.py, phonebookclient.py, phonebookserver.py, and phonebookclienthandler.py posted on the Instructor Companion Site. 100. Convert the ATM application presented in Chapter 10 to a networked application. The client (in the file atmclient.py) manages the user interface, whereas the server (in the file atmserver.py) and client handler (in the file atmclienthandler.py) manage connecting to and the transactions with the bank (in the file bank.py). Do not be concerned about synchronization problems in this exercise. (LO: 12.1, 12.3) Solution: See atmclient.py, atmserver.py, and atmclienthandler.py posted on the Instructor Companion Site. 101. Write the tester program (in the file readersandwriters.py) for readers and writers of a shared Counter object. A sample run is shown in Figure 12-4. (LO: 12.1, 12.) Solution: See readersandwriters.py and sharedcell.py, posted on the Instructor Companion Site. 102. Add synchronization to the ATM program of Programming Exerise 6. You will need to give concurrent readers access to a single account as long as a writer is not writing to it, and give a single writer access, as long as other writers and readers are not accessing the account. Hint: Just complete the

ThreadSafeSavingsAccount class discussed in this chapter (in the file threadsafesavingsaccount.py) and use it to create account objects in the Bank class. (LO: 12.1, 12.2, 12.3) Solution: See threadsafesavingsaccount.py posted on the Instructor Companion Site. 103. Jack has been working on the shared cell classes for the producer–consumer problem and the readers and writers problem, and he notices some serious redundancy in the code. The read and write methods are the same in both classes, and both classes include the same instance variable for the data. Jill, his team manager, advises him to place this redundant code in a parent class named SharedCell (in the file sharedcell.py). Then two subclasses, named PCSharedCell (in the file pcsharedcell.py) and

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

148


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

RWSharedCell (in the file rwsharedcell.py), can inherit this code and define the methods beginRead, endRead, beginWrite, and endWrite, to enforce their specific synchronization protocols. Also, the __init__ method in each subclass first calls the __init__ method in the

SharedCell class to set up the data, and then adds the condition(s) and other instance variables for its specific situation. Jack has called in sick, so you must complete this hierarchy of classes and redo the demo programs (in the files producerconsumer.py and readersandwriters.py) so that they use them. (LO: 12.1, 12.2) Solution: See sharedcell.py, pcsharedcell.py, rwsharedcell.py, producerconsumer.py, and readersandwriters.py posted on the Instructor Companion Site. 104. A crude multiclient chat room allows two or more users to converse by sending and receiving messages. On the client side (in the file chatclient.py), a user connects to the chat room as in the ATM application, by clicking a Connect button. At that point, a transcript of the conversation thus far appears in a text area. At any time, the user can send a message to the chat room by entering it as input and clicking a Send button. When the user sends a message, the chat room returns another transcript of the entire conversation to display in the text area. The user disconnects by clicking the Disconnect button. On the server side, there are five resources: a server, a client handler, a transcript, a thread-safe transcript, and a shared cell. Their roles are much the same as they are in the ATM application of Programming Exercise 8. The server (in the file chatserver.py) creates a thread-safe transcript (in the file threadsafetranscript.py) at start-up, listens for client connections, and passes a client’s socket and the thread-safe transcript to a client handler (in the file chatclienthandler.py) when a client connects. The client handler receives the client’s name from the client socket, adds this name and the connection time to the thread-safe transcript, sends the thread-safe transcript’s string to the client, and waits for a reply. When the client’s reply comes in, the client handler adds the client’s name and time to it, adds the result to the thread-safe transcript, and sends the thread-safe transcript’s string back to the client. When the client disconnects, her name and a message to that effect are added to the thread-safe transcript.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

149


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

The SharedCell class includes the usual read and write methods for a readers and writers protocol, and the SharedTranscript and Transcript classes include an add method and an

__str__ method. The add method adds a string to a list of strings, while __str__ returns the join of this list, separated by newlines. (LO: 12.1, 12.2, 12.3) Solution: See chatclient.py, chatserver.py, transcript.py, sharedtranscript.py, and chatclienthandler.py posted on the Instructor Companion Site.

DEBUGGING EXERCISE SOLUTION Jill is developing a client/server program. Her server script launches without a problem, but she receives the following error message when she launches the client’s script:

Traceback (most recent call last): File "/Users/jill/pythonfiles/client.py", line 15, in <module> server.connect(ADDRESS)

# Connect it to a host

ConnectionRefusedError: [Errno 61] Connection refused Here are the code segments in her server and client scripts that are responsible for setting up the connection:

""" File: server.py """

from socket import * from codecs import decode

HOST = "localhost" PORT = 6000 ADDRESS = (HOST, PORT)

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

150


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 12, Multithreading, Networks, and Client-Server programming

server = socket(AF_INET, SOCK_STREAM) server.bind(ADDRESS)

""" File: client.py """

from socket import * from codecs import decode

HOST = "localhost" PORT = 5000 BUFSIZE = 1024 ADDRESS = (HOST, PORT)

server = socket(AF_INET, SOCK_STREAM)

# Create a socket

server.connect(ADDRESS)

# Connect it to a host

Explain why the error occurs in Jill’s program and suggest a way to correct this error. Solution The server script and the client script each must specify an address to enable the connection between them. An address consists of a host and a port number. The host can be either an IP name or an IP number. The port number must be an integer. This address information, the host and the port number, must be exactly the same in both the server script and the client script. Jill’s server and client scripts both use "localhost" to specify the host.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

151


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

However, while her server script’s port number is 6000, her client script’s port number is 5000. Thus, the addresses formed from this information in the two scripts do not match, so her client is unable to connect to her server. To fix this error, Jill should replace the port number 5000 in her client script with 6000 to match the port number in her server script.

Solution and Answer Guide LAMBERT, FUNDAMENTALS OF PYTHON: FIRST PROGRAMS , 3E, CY24, 9780357881019; CHAPTER 13, SEARCHING, SORTING, AND COMPLEXITY ANALYSIS

TABLE OF CONTENTS Exercise Solutions ................................................................................................................................... 152 Exercise 13.1 ......................................................................................................................................... 152 Exercise 13.2 ......................................................................................................................................... 153 Exercise 13.3 ......................................................................................................................................... 154 Exercise 13.4 ......................................................................................................................................... 154 Exercise 13.5 ......................................................................................................................................... 155 Review Questions Answers..................................................................................................................... 156 Programming Exercises Solutions ......................................................................................................... 161

EXERCISE SOLUTIONS EXERCISE 13.1 52. Write a tester program that counts and displays the number of iterations of the following loop:

while problemSize > 0: problemSize = problemSize // 2 Solution:

problemSize = int(input("Enter the problem size: ")) count = 0 while problemSize > 0: problemSize = problemSize // 2 count += 1 print(count)

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

152


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

53. Run the program you created in Exercise 13.1 using problem sizes of 1000, 2000, 4000, 10,000, and 100,000. As the problem size doubles or increases by a factor of 10, what happens to the number of iterations? Solution: When the problem size doubles, the number of iterations increases by 1. When the problem increases by a factor of 10, the number of iterations increases by 3. 54. The difference between the results of two calls of the time function time() is an elapsed time. Because the operating system might use the CPU for part of this time, the elapsed time might not reflect the actual time that a Python code segment uses the CPU. Browse the Python documentation for an alternative way of recording the processing time and describe how this would be done. Solution: According to the Python documentation, the function time.process_time can be used to measure the time that a process actually uses the CPU, without including the time that the process sleeps.

EXERCISE 13.2 22. Assume that each of the following expressions indicates the number of operations performed by an algorithm for a problem size of n. Point out the dominant term of each algorithm and use big-O notation to classify it. a. b. c.

2n – 4n2 + 5n 3n2 + 6 n3 + n2 – n

Solution: a. b. c.

2n, O(n) 3n2, O(n2) n3, O(n3)

23. For problem size n, algorithms A and B perform n2 and ½ n2 + ½ n instructions, respectively. Which algorithm does more work? Are there particular problem sizes for which one algorithm performs significantly better than the other? Are there particular problem sizes for which both algorithms perform approximately the same amount of work? Solution: Algorithm A does more work, on all problem sizes. 24. At what point does an n4 algorithm begin to perform better than a 2n algorithm? Solution: When n is 16, then n4 and 2n are the same, 65536. When n is 17, n4 is 83521 and 2n is 131072.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

153


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

EXERCISE 13.3 16. Suppose that a list contains the values 20 44 48 55 62 66 74 88 93 99

at index positions 0 through 9. Trace the values of the variables left, right, and midpoint in a binary search of this list for the target value 90. Repeat for the target value 44. Solution: Trace of first run: left right midpoint 0 9 4 5 9 7 8 9 8 Trace of second run: left right midpoint 0 9 4 0 3 1 17. The method we usually use to look up an entry in a phone book is not exactly the same as a binary search because, when using a phone book, we don’t always go to the midpoint of the sublist being searched. Instead, we estimate the position of the target based on the alphabetical position of the first letter of the person’s last name. For example, when we are looking up a number for ―Smith,‖ we first look toward the middle of the second half of the phone book, instead of in the middle of the entire book. Suggest a modification of the binary search algorithm that emulates this strategy for a list of names. Is its computational complexity any better than that of the standard binary search? Solution: Let’s assume, somewhat unrealistically, that the names are distributed evenly through the list (as many beginning with ―A‖ as with ―B,‖ and so forth) and that there are thousands of names in the list. Then, on the first pass of the search, the midpoint will be a function of the size of the list and the ordinal value of the target name’s first letter. The first pass will eliminate many more elements than before, and the other passes, if they are necessary, will have smaller search spaces as well. However, the modified algorithm is still closer to O(lg n) than to O(1) in the worst case.

EXERCISE 13.4 1.

Which configuration of data in a list causes the smallest number of exchanges in a selection sort? Which configuration of data causes the largest number of exchanges values?

Solution: A sorted list causes the fewest exchanges in selection sort (0). A list with the largest item as the first one and the rest of the items in ascending order causes the greatest number of exchanges (n – 1).

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

154


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

2.

Explain the role that the number of data exchanges plays in the analysis of selection sort and bubble sort. What role, if any, does the size of the data objects play? Solution: The worst-case number of exchanges in selection sort (n – 1) does not predominate, so there is little impact on performance. The worst-case number of exchanges in bubble sort (approximately n2) is similar to the worst-case complexity, so there is significant extra work. The size of the elements has no impact, because references only are exchanged.

3.

Explain why the modified bubble sort still exhibits O(n2) behavior on the average. Solution: The configurations of the list that cause the sort to terminate early are relatively rare, so on most of the cases, the outer loop does not terminate early.

4.

Explain why insertion sort works well on partially sorted lists. Solution: In partially sorted lists, the insertion points for elements are found more quickly in the inner loop, reducing the amount of work done.

EXERCISE 13.5 1.

Describe the strategy of quicksort and explain why it can reduce the time complexity of sorting from O(n2) to O(n log n).

Solution: The strategy of quicksort begins by selecting a pivot element from the current sublist. The algorithm then rearranges the other elements around the pivot, such that the smaller ones are to its left and the larger ones are to its right. After this partition has been accomplished, the algorithm is run recursively on the sublists to the right and left of the pivot. The algorithm halts when the length of its sublist is 1. The total number of comparisons at each level of partitioning is approximately n. In the best case, there are log2n levels of partitions, so the best-case complexity of quicksort is O(n log n).

2.

Why is quicksort not O(n log n) in all cases? Describe the worst-case situation for quicksort and give a list of 10 integers, 1–10, that would produce this behavior. Solution: Quicksort is not O(n log n) in all cases. In the worst case, all of the partitions are so uneven that the complexity degrades to O(n2). For example, this occurs when the list is already sorted and the pivot is always the first item.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

155


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

3.

The partition operation in quicksort chooses the item at the midpoint as the pivot. Describe two other strategies for selecting a pivot value. Solution: Selecting an element at random or selecting the median element of the first three elements are two alternative ways of selecting a pivot.

4.

Jill has a bright idea: When the length of a sublist in quicksort is less than a certain number—say, 30 items—run an insertion sort to process that sublist. Explain why this is a bright idea. Solution: Insertion sort performs better as its list is more thoroughly sorted. Because quicksort has already shifted elements into positions that are close to where they should be, running insertion sort on the medium-sized sublists might finish the job faster than continuing quicksort all the way down.

5.

Why is merge sort an O(n log n) algorithm in the worst case? Solution: Merge sort is O(n log n) in the worst case because the subdivisions during recursive descent are always even.

REVIEW QUESTIONS ANSWERS 71. Timing an algorithm with different problem sizes cc. can give you a general idea of the algorithm’s run-time behavior dd. can give you an idea of the algorithm’s run-time behavior on a particular hardware platform ee. can give you an idea of the algorithm’s run-time behavior on a particular software platform ff. provides no indication of the algorithm’s run-time behavior Answer: b Feedback: aaa. Incorrect. Running times may vary from hardware platform to hardware platform. bbb. Correct. The hardware platform has a significant effect on running time. ccc. Incorrect. The software platform may produce similar running times across different hardware platforms. ddd. Incorrect. Timing an algorithm does reveal how it performs with different data sets. 72. Counting instructions a.

provides the same data on different hardware and software platforms

b.

can demonstrate the impracticality of exponential algorithms with large problem sizes

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

156


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

c.

is impractical

d.

provides no indication of the algorithm’s run-time behavior

Answer: a Feedback: ss. Correct. The counts do not change across platforms. tt. Incorrect. This requires further analysis. uu. Incorrect. It’s easy to do. vv. Incorrect The variance of instruction counts with data sizes can show trends in behavior. 73. The expressions O(n), O(n2), and O(kn) are, respectively, a.

exponential, linear, and quadratic

b.

linear, quadratic, and exponential

c.

logarithmic, linear, and quadratic

d.

constant, linear, and quadratic

Answer: b Feedback: ss. Incorrect. O(n) is linear, O(n2) is quadratic, and O(kn) is exponential. tt. Correct. O(n) is linear, O(n2) is quadratic, and O(kn) is exponential. uu. Incorrect. O(n) is linear, O(n2) is quadratic, and O(kn) is exponential. vv. Incorrect. O(n) is linear, O(n2) is quadratic, and O(kn) is exponential.

74. A binary search a.

assumes that the data are arranged in no particular order

b.

assumes that the data are sorted

c.

assumes that the data values are unique

d.

assumes that the data do not recognize the comparison operators

Answer: b Feedback:

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

157


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

ss. Incorrect. Binary search depends on the ordering of the data. tt.

Correct. Binary search depends on the ordering of the data.

uu. Incorrect. Binary search tolerates duplicate data values. vv. Incorrect. Comparisons are required for binary search.

75. A selection sort makes at most a.

n3 exchanges of data items

b.

n2 exchanges of data items

c.

n exchanges of data items

d.

one exchange of data items

Answer: c Feedback: u.

Incorrect. Exchanges are only made in the outer loop, which makes n passes.

v.

Incorrect. Exchanges are only made in the outer loop, which makes n passes.

w. Correct. Up to n – 1 exchanges might be made, in the worst case. x.

Incorrect. Up to n – 1 exchanges might be made, in the worst case.

76. The best-case behavior of insertion sort and modified bubble sort is a.

constant

b.

linear

c.

quadratic

d.

exponential

Answer: b Feedback: ss. Incorrect. n comparisons are required to determine that the list is already sorted. tt.

Correct. n comparisons are required to determine that the list is already sorted.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

158


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

uu. Incorrect. n comparisons are required to determine that the list is already sorted. vv. Incorrect. n comparisons are required to determine that the list is already sorted. 77. An example of an algorithm whose best-case, average-case, and worst-case behaviors are the same is a.

sequential search

b.

insertion sort

c.

selection sort

d.

quicksort

Answer: c Feedback: e.

Incorrect. Best case is constant, worst case is linear.

f.

Incorrect. Best case is linear, average case is quadratic.

g.

Correct. Comparisons predominate, and there are always n2 of them.

h.

Incorrect. Average case is n log n, worst case is n2.

78. Generally speaking, it is better to a.

tweak an algorithm to shave a few seconds of running time

b.

choose an algorithm with the lowest order of computational complexity

c.

choose a recursive algorithm over an algorithm that uses a loop

d.

make no changes to an algorithm to improve its efficiency

Answer: b Feedback: e.

Incorrect. Tweaking will not reduce an algorithm’s computational complexity.

f.

Correct. An algorithm with a lower order of computational complexity will have a dramatically better running time than competing algorithms.

g.

Incorrect. Recursive algorithms require more runtime overhead than loop-based algorithms.

h.

Incorrect. If a change can be made to improve and algorithm’s efficiency, that change should be made.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

159


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

79. The recursive Fibonacci function makes approximately a.

n recursive calls for problems of a large size n

b.

n2 recursive calls for problems of a large size n

c.

n3 recursive calls for problems of a large size n

d.

2n recursive calls for problems of a large size n

Answer: d Feedback: u.

Incorrect. The call tree for recursive Fibonacci shows that the number of calls at each level (as n grows by 1) is almost double the number of calls at the previous level. Thus, the growth of work is much greater than n.

v.

Incorrect. The call tree for recursive Fibonacci shows that the number of calls at each level (as n grows by 1) is almost double the number of calls at the previous level. Thus, the growth of work is much greater than n2.

w. Incorrect. The call tree for recursive Fibonacci shows that the number of calls at each level (as n grows by 1) is double the number of calls at the previous level. Thus, the growth of work is much greater than n3. x.

Correct. The call tree for recursive Fibonacci shows that the number of calls at each level (as n grows by 1) is almost double the number of calls at the previous level. Thus, the growth of work approximates 2n.

80. Each level in a completely filled binary call tree has a.

four times as many calls as the level above it

b.

three times as many calls as the level above it

c.

twice as many calls as the level above it

d.

the same number of calls as the level above it

Answer: c Feedback: q.

Incorrect. Each node in the tree has exactly two children, so the multiple for the levels is 2, not 4.

r.

Incorrect. Each node in the tree has exactly two children, so the multiple for the levels is 2, not 3.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

160


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

s.

Correct. Each node in the tree has exactly two children, so the multiple for the levels is 2.

t.

Incorrect. Each node in the tree has exactly two children, so the multiple for the levels is 2, not 1.

PROGRAMMING EXERCISES SOLUTIONS For all Programming Exercises Solutions, see solution files posted on the Instructor Companion Site. 105. A sequential search of a sorted list can halt when the target is less than a given element in the list. Define a modified version of this algorithm (in the file search.py), and state the computational complexity, using big-O notation, of its best-, worst-, and average-case performances. (LO: 13.2, 13.3) Solution: See search.py posted on the Instructor Companion Site. 106. The list method reverse reverses the elements in the list. Define a function named reverse (in the file reverse.py) that reverses the elements in its list argument (without using the method reverse!). Try to make this function as efficient as possible, and state its computational complexity using big-O notation. (LO: 13.2) Solution: See reverse.py posted on the Instructor Companion Site 107. Python’s pow function returns the result of raising a number to a given power. Define a function expo (in the file expo.py) that performs this task and state its computational complexity using big-O notation. The first argument of this function is the number, and the second argument is the exponent (nonnegative numbers only). You may use either a loop or a recursive function in your implementation. Caution: Do not use Python’s ** operator or pow function in this exercise! (LO: 13.2) Solution: See expo.py posted on the Instructor Companion Site. 108. An alternative strategy for the expo function uses the following recursive definition:

expo(number, exponent) = 1, when exponent = 0 = number * expo(number, exponent – 1), when exponent is odd

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

161


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

= (expo(number, exponent // 2))2, when exponent is even Define a recursive function expo (in the file expo.py) that uses this strategy and state its computational complexity using big-O notation. (LO: 13.2, 13.3) Solution: See expo.py posted on the Instructor Companion Site. 109. Python’s list method sort includes the keyword argument reverse, whose default value is False. The programmer can override this value to sort a list in descending order. Modify the selectionSort function (in the file sort.py) discussed in this chapter so that it allows the programmer to supply this additional argument to redirect the sort. (LO: 13.4) Solution: See sort.py posted on the Instructor Companion Site. 110. Modify the recursive Fibonacci function (in the file fib.py) to employ the memoization technique discussed in this chapter. The function creates a dictionary and then defines a nested recursive helper function. The base case is the same as before. However, before making a recursive call, the helper function looks up the value for the function’s current argument in the dictionary (use the method get, with None as the default value). If the value exists, the function returns it. Otherwise, after the helper function adds the results of its two recursive calls, it saves the sum in the dictionary with the current argument of the function as the key. Also use the Counter object discussed in this chapter to count the number of recursive calls of the helper function. (LO: 13.2, 13.6) Solution: See fib.py posted on the Instructor Companion Site. 111. Profile the performance of the memoized version of the Fibonacci function defined in Programming Exercise 6. The function (in the file fib.py) should count the number of recursive calls. State its computational complexity using big-O notation and justify your answer. (LO: 13.1, 13.2, 13.6) Solution: See fib.py posted on the Instructor Companion Site. 112. The function makeRandomList creates and returns a list of numbers of a given size (its argument). The numbers in the list are unique and range from 1 through the size. They are placed in random order. Here is the code for the function:

def makeRandomList(size):

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

162


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

lyst = [] for count in range(size): while True: number = random.randint(1, size) if not number in lyst: lyst.append(number) break return lyst You may assume that range, randint, and append are constant time functions. You may also assume that random.randint more rarely returns duplicate numbers as the range between its arguments increases. State the computational complexity of this function using big-O notation and justify your answer. (LO: 13.2, 13.6)) Solution: See 13.8.txt posted on the Instructor Companion Site. 113. As discussed in Chapter 7, a computer supports the calls of recursive functions using a structure called the call stack. Generally speaking, the computer reserves a constant amount of memory for each call of a function. Thus, the memory used by a recursive function can be subjected to complexity analysis. State the computational complexity of the memory used by the recursive factorial and Fibonacci functions, as defined in Chapter 7. (LO: 13.2, 13.6) Solution: See 13.9.txt posted on the Instructor Companion Site. 114. The function that draws c-curves, and which was discussed in Chapter 8, has two recursive calls. Here is the code:

def cCurve(t, x1, y1, x2, y2, level): def drawLine(x1, y1, x2, y2): """Draws a line segment between the endpoints.""" t.up() t.goto(x1, y1)

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

163


Solution and Answer Guide: Lambert, Fundamentals of Python: First Programs, 3e, CY24, 9780357881019; Chapter 13, Searching, Sorting, and Complexity Analysis

t.down() t.goto(x2, y2) if level == 0: drawLine(x1, y1, x2, y2) else: xm = (x1 + x2 + y1 - y2) // 2 ym = (x2 + y1 + y2 - x1) // 2 cCurve(t, x1, y1, xm, ym, level - 1) cCurve(t, xm, ym, x2, y2, level - 1) You can assume that the function drawLine runs in constant time. State the computational complexity of the cCurve function, in terms of the level, using big-O notation. Also, draw a call tree for a call of this function with a level of 3. (LO: 13.2, 13.6) Solution: See 13.10.txt and 13.10.png posted on the Instructor Companion Site.

© 2024 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

164


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.