Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
CLEVELAND
INSTITUTE OF
ELECTRONICS
INTRODUCTION TO PROGRAMMING IN PYTHON LESSONS 9301C THROUGH 9310C
1
Study Guide to accompany Fundamentals of Python – From First Programs Through Data
Structures
By Kenneth A. Lambert
ISBN 10: 1423902181
ISBN 13: 9781423902188
This study guide contains excerpts from the Fundamentals of Python Instructor's resources and the book Fundamentals of Python – From First Programs through Data Structures by Kenneth Lambert
© Copyright 2012 Cleveland Institute of Electronics All Rights Reserved / Printed in the United States of America
FIRST EDITION / First Printing / March 2012
2
Contents Chat with Your Instructor ......................................................................................................... 3
Chapter 1 - Introduction ............................................................................................................ 4
Chapter 2 - Software Development, Data Types, and Expressions ...................................... 11 Python Lesson 9301C Exam ................................................................................................................. 17
Chapter 3 - Control Statements ................................................................................................. 2 Python Lesson 9302C Exam ................................................................................................................... 7
Chapter 4 - Strings and Text Files........................................................................................... 10
Chapter 5 - Lists and Dictionaries ........................................................................................... 14 Python Lesson 9303C Exam ................................................................................................................. 19
Chapter 6 - Design with Functions .......................................................................................... 21 Python Lesson 9304C Exam ................................................................................................................. 27
Chapter 7 - Simple Graphics and Image Processing ............................................................. 30 Python Lesson 9305C Exam ................................................................................................................. 34
Chapter 8 - Design with Classes .............................................................................................. 37 Python Lesson 9306C Exam ................................................................................................................. 43
Chapter 9 - Graphical User Interfaces.................................................................................... 46 Python Lesson 9307C Exam ................................................................................................................. 50
Chapter 11 - Searching, Sorting, and Complexity Analysis.................................................. 53
Chapter 13 - Collections, Arrays, and Linked Structures .................................................... 58 Python Lesson 9308C Exam ................................................................................................................. 64
Chapter 14 - Linear Collections: Stacks ................................................................................. 67 Python Lesson 9309C Exam ................................................................................................................. 72
Chapter 16 - Linear Collections: Lists .................................................................................... 75
Chapter 18 - Hierarchical Collections: Trees ......................................................................... 81 Python Lesson 9310C Exam ................................................................................................................. 87
Appendix - Quick Quiz Answers ............................................................................................. 90
3
Chat with Your Instructor
The Study Guide for Fundamentals in Python is created to provide you with concepts, ideas and
pointers for learning about computer programming in Python. Chapter outlines are included
followed by topic ideas presented in a chapter-by-chapter format, which include the following:
Quick Quizzes
Additional Resources
Key Terms definitions
The topics follow the section-by-section format of the book and are intended to give you a range of
ideas for your understanding.
Students often learn from investigation of programming topics. For this reason, there are many
topic tips throughout this guide. These topic tips may require you to solve a problem, work through
a new direction in technology or even attempt to predict the future. All of the topic tips are meant
to be thought provoking and to help you apply what you are learning.
Each chapter in the Study Guide also includes a set of interesting Additional Resources, which are
Web links to topics of interest. Finally, a list of definitions of Key Terms is included for each
chapter.
Fundamentals in Python – From First Programs through Data Structures, covers many exciting
topics, and the staff believes that you will share in the excitement.
If you have a technical problem, we recommend the following:
First, check the textbook that accompanies the software.
Many software products include on-line help. If the answer is not available in the printed
materials, try using the Help feature of your software.
Feel free to call the instruction department during business hours (8:30 AM to 6 PM
Eastern time), Monday through Friday, and Saturday during the weekend hours (8:30 AM
to 5 PM Eastern time). Be prepared to describe which lesson you're working on and the
problem you're having.
Instructional Support Addresses and Phone Numbers
Main Support Help Line: (800) 243-6446 or (216) 781-9400
E-mail address: [email protected]
Instructional Support is available business hours (Eastern time) Monday through Saturday.
Mailing address: Cleveland Institute of Electronics
1776 East 17th
Street
Cleveland, OH 44114
4
Chapter 1 - Introduction
LESSON 9301C
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Chapter Notes
Overview
Chapter 1 describes the basic features of an algorithm. You learn how hardware and
software collaborate in a computer’s architecture. A brief history of computing is provided.
Finally, you learn how to compose and run a simple Python program.
Objectives
After completing this chapter, you will be able to:
Describe the basic features of an algorithm
Explain how hardware and software collaborate in a computer’s architecture
Give a brief history of computing
Compose and run a simple Python program
Topic Tips
Two Fundamental Ideas of Computer Science: Algorithms and Information
Processing
5
Topic Tip For a more information on algorithms and their history, read:
http://en.wikipedia.org/wiki/Algorithm.
The Structure of a Modern Computer System
Topic Tip For more on computer software, read: http://en.wikipedia.org/wiki/Software.
Quick Quiz 1
1. What is an algorithm?
2. The part of a computer that is responsible for processing data is the
____________________ (CPU).
3. True or False: A program stored in computer memory must be represented in binary digits,
which is also known as machine code.
4. A modern ____________________ (GUI) organizes the monitor screen around the
metaphor of a desktop, with windows containing icons for folders, files, and applications.
A Not-So-Brief History of Computing Systems
Topic Tip For a brief history of computer languages and their evolution, read the following:
http://www.scriptol.org/history.php.
Topic Tip You can find a graph that illustrates Moore’s Law at the following site:
http://en.wikipedia.org/wiki/Moore's_law.
Quick Quiz 2
1. In the late 1930s, ____________________ (1916–2001), a mathematician and electrical
engineer at M.I.T., wrote a classic paper titled “A Symbolic Analysis of Relay and
Switching Circuits.”
2. True or False: In the early 1970s, computer scientists realized that a symbolic notation
could be used instead of machine code, and the first assembly languages appeared.
3. What is Moore’s Law?
6
4. By the mid 1980s, the ____________________ had grown into what we now call the
Internet, connecting computers owned by large institutions, small organizations, and
individuals all over the world.
Getting Started with Python Programming
Topic Tip Python is an interpreted language. If you are familiar with other interpreted
languages, compare them to Python.
Topic Tip A good Python programming tutorial is available at: http://docs.python.org/tut/.
Quick Quiz 3
1. The easiest way to open a Python shell is to launch the ____________________.
2. What is a shell prompt?
3. True or False: In Python, to begin the next output on the same line as the previous one, you
can place a colon at the end of the earlier print statement.
4. The term ___________________ refers to the rules for forming sentences in a language.
Additional Resources
1. History and evolution of computer languages:
www.scriptol.org/history.php
2. Algorithm:
http://en.wikipedia.org/wiki/Algorithm
3. Software:
http://en.wikipedia.org/wiki/Software
4. Python Tutorial:
http://docs.python.org/tut/
Key Terms
abacus: An early computing device that allowed users to perform simple calculations by
moving beads along wires.
abstraction: A simplified view of a task or data structure that ignores complex detail.
7
algorithm(s): A finite sequence of instructions that, when applied to a problem, will solve
it.
Analytical Engine: A general-purpose computer designed in the nineteenth century by
Charles Babbage, but never completed by him.
application software: Programs that allow human users to accomplish specialized tasks,
such as word processing or database management.
argument: A value or expression passed in a function or method call.
artificial intelligence: A field of computer science whose goal is to build machines that can
perform tasks that require human intelligence.
assembler: A program that translates an assembly language program to machine code.
assembly language: A computer language that allows the programmer to express
operations and memory addresses with mnemonic symbols.
batch processing: The scheduling of multiple programs so that they run in sequence on the
same computer.
binary digit: A digit, either 0 or 1, in the binary number system. Program instructions are
stored in memory using a sequence of binary digits. See also bit.
bit: A binary digit.
bitmap: A data structure used to represent the values and positions of points on a computer
screen or image.
bit-mapped display screen: A type of display screen that supports the display of graphics
and images.
byte: A sequence of bits used to encode a character in memory.
byte code: The kind of object code generated by a Python compiler and interpreted by a
Python virtual machine. Byte code is platform independent.
card reader: A device that inputs information from punched cards into the memory of a
computer.
coding: The process of writing executable statements that are part of a program to solve a
problem. See also implementation.
compiler: A computer program that automatically converts instructions in a high-level
language to byte code or machine language.
computing agent: The entity that executes instructions in an algorithm.
concurrent processing: The simultaneous performance of two or more tasks.
data: The symbols that are used to represent information in a form suitable for storage,
processing, and communication.
data validation: The process of examining data prior to its use in a program.
execute: To carry out the instructions of a program.
external (or secondary) memory: Memory that can store large quantities of data
permanently.
file system: Software that organizes data on secondary storage media.
GUI (graphical user interface): A means of communication between human beings and
computers that uses a pointing device for input and a bitmapped screen for output. The
bitmap displays images of windows and window objects such as buttons, text fields, and
drop-down menus. The user interacts with the interface by using the mouse to directly
manipulate the window objects. See also window object.
hardware: The computing machine and its support devices.
high-level programming language: Any programming language that uses words and
symbols to make it relatively easy to read and write a program. See also assembly language
and machine language.
HTML (HyperText Markup Language): A programming language that allows the user to
create pages for the World Wide Web.
8
hypermedia: A data structure that allows the user to access different kinds of information
(text, images, sound, video, applications) by traversing links.
hypertext: A data structure that allows the user to access different chunks of text by
traversing links.
identifiers: Words that must be created according to a well-defined set of rules but can
have any meaning subject to these rules.
IDE (integrated development environment): A set of software tools that allows you to
edit, compile, run, and debug programs within one user interface.
information processing: The transformation of one piece of information into another piece
of information.
input: Data obtained by a program during its execution.
input device: A device that provides information to the computer. Typical input devices are
a mouse, keyboard, disk drive, microphone, and network port. See also I/O device and
output device.
integrated circuit: The arrangement of computer hardware components in a single,
miniaturized unit.
interpreter: A program that translates and executes another program.
I/O device: Any device that allows information to be transmitted to or from a computer.
See also input device and output device.
keypunch machine: An early input device that allowed the user to enter programs and data
onto punched cards.
library: A collection of operations and data organized to perform a set of related tasks.
linear: An increase of work or memory in direct proportion to the size of a problem.
loader: A system software tool that places program instructions and data into the
appropriate memory locations before program start-up.
machine language: The language used directly by the computer in all its calculations and
processing. Also called machine code.
magnetic storage media: Any media that allow data to be stored as patterns in a magnetic
field.
main (primary or internal) memory: The high-speed internal memory of a computer, also
referred to as random access memory (RAM). See also memory and secondary memory.
mainframe: Large computers typically used by major companies and universities.
memory: The ordered sequence of storage cells that can be accessed by address.
Instructions and variables of an executing program are temporarily held here. See also main
memory.
memory location: A storage cell that can be accessed by address.
microcomputer: A computer capable of fitting on a laptop or desktop, generally used by
one person at a time.
minicomputer: A small version of a mainframe computer. It is usually used by several
people at once.
Moore’s Law: A hypothesis that states that the processing speed and storage capacity of
computers will increase by a factor of two every 18 months.
network: A collection of resources that are linked together for communication.
newline character: A special character (‘\n’) used to indicate the end of a line of characters
in a string or a file stream.
operating system: A large program that allows the user to communicate with the hardware
and performs various management tasks.
optical storage media: Devices such as CDs and DVDs that store data permanently and
from which the data are accessed by using laser technology.
output: Information that is produced by a program.
9
output device: A device that allows you to see the results of a program. Typically, it is a
monitor, printer, speaker, or network port.
port: A channel through which several clients can exchange data with the same server or
with different servers.
program: A set of instructions that tells the machine (the hardware) what to do.
program library: A collection of operations and data organized to perform a set of related
tasks.
programming language: A formal language that computer scientists use to give
instructions to the computer.
PVM (Python Virtual Machine): A program that interprets Python byte codes and
executes them.
RAM (random access memory): High-speed memory where programs and their data
reside during program execution.
run-time system: Software that supports the execution of a program.
script: A Python program that can be launched from a computer’s operating system.
secondary (external) memory: An auxiliary device for memory, usually a disk or
magnetic tape.
semiconductor storage media: Devices, such as flash sticks, that use solid state circuitry
to store data permanently.
shell: A program that allows users to enter and run Python program expressions and
statements interactively.
software: Programs that make the machine (the hardware) do something, such as word
processing, database management, or games.
software reuse: The process of building and maintaining software systems out of existing
software components.
solid-state device: An electronic device, typically based on a transistor, which has no
moving parts.
source code: The program text as viewed by the human being who creates or reads it, prior
to compilation.
statement: An individual instruction in a program.
syntax: The rules for constructing well-formed programs in a language. Also, the rules for
forming sentences in a language.
syntax error: An error in spelling, punctuation, or placement of certain key symbols in a
program. See also compilation error, design error, and run time error.
system software: The programs that allow users to write and execute other programs,
including operating systems such as Windows and Mac OS.
terminal I/O interface: A user interface that allows the user to enter input from a keyboard
and view output as text in a window. Also called a terminal-based interface.
text editor: A program that allows the user to enter text, such as a program, and save it in a
file.
time sharing: The scheduling of multiple programs so that they run concurrently on the
same computer.
time-sharing operating system: A computer system that can run multiple programs in
such a manner that its users have the illusion that they are running simultaneously.
transistor: A device with no moving parts that can hold an electromagnetic signal and that
is used to build computer circuitry for memory and a processor.
translator: A program that converts a program written in one language to an equivalent
program in another language.
user interface: The part of a software system that handles interaction with users.
10
variable: A memory location, referenced by an identifier, whose value can be changed
during execution of a program.
virtual machine: A software tool that behaves like a high-level computer.
virtual reality: A technology that allows a user to interact with a computer-generated
environment, usually simulating movement in three dimensions.
Web client: Software on a user’s computer that makes requests for resources from the
Web.
Web server: Software on a computer that responds to requests for resources and makes
them available on the Web.
window: A rectangular area of a computer screen that can contain window objects.
Windows typically can be resized, minimized, maximized, zoomed, or closed.
Continue to the next chapter for the lesson exam
11
Chapter 2 - Software Development, Data Types, and
Expressions
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Lesson Assignment
Chapter Notes
Overview
Chapter 2 covers topics related to software development, data types, and expressions. You
first learn about the basic phases of the software development process. Next, you learn how
to use strings, integer, and floating point numbers in Python. Simple as well as mixed-mode
arithmetic expressions are covered. Finally, you learn about modules, how to import
functions from library modules, and how to call functions with arguments and use the
returned values appropriately.
Objectives
After completing this chapter, you will be able to:
Describe the basic phases of software development: analysis, design, coding, and testing
Use strings for the terminal input and output of text
Use integers and floating point numbers in arithmetic operations
Construct arithmetic expressions
Initialize and use variables with appropriate names
Import functions from library modules
12
Call functions with arguments and use returned values appropriately
Construct a simple Python program that performs inputs, calculations, and outputs
Use docstrings to document Python programs
Topic Tips
The Software Development Process
Topic Tip For more information on the software development process, visit:
http://en.wikipedia.org/wiki/Software_development_process.
Strings, Assignment, and Comments
Topic Tip For more information about string literals, visit:
http://docs.python.org/ref/strings.html.
Topic Tip
CamelCase is a standard identifier naming convention for several programming
languages. For more information, visit:
http://en.wikipedia.org/wiki/CamelCase.
Topic Tip
The pydoc module can be used to display information about a Python object,
including its docstring. For more information, visit:
http://epydoc.sourceforge.net/docstrings.html.
Quick Quiz 1
1. Modern software development is usually incremental and ____________________.
2. What is a correct program?
3. True or False: In programming, a data type consists of a set of values and a set of
operations that can be performed on those values.
4. The newline character ____________________ is called an escape sequence.
Numeric Data Types and Character Sets
Topic Tip Complex numbers are also supported in Python. For more information, read the
following: http://docs.python.org/tut/node5.html.
13
Topic Tip You can find more information about Python’s Unicode support at:
http://www.amk.ca/python/howto/unicode.
Quick Quiz 2
1. Real numbers have ____________________ precision, which means that the digits in the
fractional part can continue forever.
2. True or False: In the 1960s, the original ASCII set encoded each keyboard character and
several control characters using the integers from 0 through 255.
3. True or False: The precedence rules you learned in algebra apply during the evaluation of
arithmetic expressions in Python.
4. Exponentiation and assignment operations are right ____________________, so
consecutive instances of these are evaluated from right to left.
Using Functions and Modules
Topic Tip Python’s global module index is available at:
http://docs.python.org/modindex.html.
Topic Tip
“A module can contain executable statements as well as function definitions.
These statements are intended to initialize the module. They are executed only
the first time the module is imported somewhere.”
Reference: http://docs.python.org/tut/node8.html
Quick Quiz 3
1. What is a module?
2. A(n) ____________________ is a chunk of code that can be called by name to perform a
task.
3. True or False: Arguments are also known as literals.
4. The statement ____________________ would import all of the math module’s resources.
Additional Resources
1. String Literals:
http://docs.python.org/ref/strings.html
14
2. Python Docstrings:
http://epydoc.sourceforge.net/docstrings.html
3. Unicode HOWTO:
http://www.amk.ca/python/howto/unicode
4. Global Module Index:
http://docs.python.org/modindex.html
Key Terms
abstraction: A simplified view of a task or data structure that ignores complex detail.
arithmetic expression: A sequence of operands and operators that computes a value.
ASCII character set: The American Standard Code for Information Interchange ordering
for a character set.
assignment statement: A method of giving values to variables.
assignment operator: The symbol -, which is used to give a value to a variable.
character set: The list of characters available for data and program statements.
coding: The process of writing executable statements that are part of a program to solve a
problem. See also implementation.
comments: Nonexecutable statements used to make a program more readable.
concatenation: An operation in which the contents of one sequence are placed after the
contents of another sequence.
content-based operation: An operation that involves a search for a given element
irrespective of its position in a collection.
correct program: A program that produces an expected output for any legitimate input.
data type(s): A set of values and operations on those values.
default behavior: Behavior that is expected and provided under normal circumstances.
design: The phase of the software life cycle in which the programmer describes how the
program will accomplish its tasks.
design error: An error such that a program runs, but unexpected results are produced. Also
referred to as a logic error.
docstring: A sequence of characters enclosed in triple quotation marks (“““) that Python
uses to document program components such as modules, classes, methods, and functions.
empty string: A string that contains no characters.
end-of-line comment: Part of a single line of text in a program that is not executed, but
serves as documentation for readers.
escape sequence: A sequence of two characters in a string, the first of which is /. The
sequence stands for another character, such as the tab or newline.
expression: A description of a computation that produces a value.
float: A Python data type used to represent numbers with a decimal point, for example, a
real number or a floating-point number.
floating-point number: A data type that represents real numbers in a computer program.
function(s): A chunk of code that can be treated as a unit and called to perform a task.
IDE (integrated development environment): A set of software tools that allows you to
edit, compile, run, and debug programs within one user interface.
15
infinite recursion: In a running program, the state that occurs when a recursive function
cannot reach a stopping state.
integer: A positive or negative whole number, or the number 0. The magnitude of an
integer is limited by a computer’s memory.
integer arithmetic operations: Operations allowed on data of type int. These include the
operations of addition, subtraction, multiplication, division, and modulus to produce integer
answers.
left associative: The property of an operator such that repeated applications of it are
evaluated from left to right (first to last).
literal: An element of a language that evaluates to itself, such as 34 or “hi there.”.
main module: The software component that contains the point of entry or start-up code of
a program.
mixed-mode arithmetic: Expressions containing data of different types; the values of these
expressions will be of either type, depending on the rules for evaluating them.
module(s): An independent program component that can contain variables, functions, and
classes.
negation: The use of the logical operator not with a Boolean expression, returning True if
the expression is false, and False if the expression is true.
newline character: A special character (‘\n’) used to indicate the end of a line of characters
in a string or a file stream.
optional arguments: Arguments to a function or method that may be omitted.
precedence rules: Rules that govern the order in which operators are applied in
expressions.
prototype: A trimmed-down version of a class or software system that still functions and
allows the programmer to study its essential features.
pseudocode: A stylized half-English, half-code language written in English but suggesting
program code.
required arguments: Arguments that must be supplied by the programmer when a
function or method is called.
returning a value: The process whereby a function or method makes the value that it
computes available to the rest of the program.
scientific notation: The representation of a floating-point number that uses a decimal point
and an exponent to express its value.
semantic error: A type of error that occurs when the computer cannot carry out the
instruction specified.
semantics: The rules for interpreting the meaning of a program in a language.
software development life cycle (SDLC): The process of development, maintenance, and
demise of a software system. Phases include analysis, design, coding, testing/verification,
maintenance, and obsolescence.
string(s) (string literals): One or more characters, enclosed in double quotation marks,
used as a constant in a program.
strongly-typed programming language: A language in which the types of operands are
checked prior to applying an operator to them, and which disallows such applications,
either at run time or at compile time, when operands are not of the appropriate type.
symbolic constant: A name that receives a value at program start-up and whose value
cannot be changed.
test suite: A set of test cases that exercise the capabilities of a software component.
type conversion function: A function that takes one type of data as an argument and
returns the same data represented in another type.
16
Unicode: A character set that uses 16 bits to represent over 65,000 possible characters.
These include the ASCII character set as well as symbols and ideograms in many
international languages.
variable: A memory location, referenced by an identifier, whose value can be changed
during execution of a program.
variable reference: The process whereby the computer looks up and returns the value of a
variable.
waterfall model: A series of steps in which a software system trickles down from analysis
to design to implementation. See also software development life cycle.
17
Python Lesson 9301C Exam
Please complete the following exam. You may use the electronic grading system for quicker
response. Simply log on to www.study-electronics.com and enter your credentials. Once the exam
has been submitted, your results will be returned within 72 hours. You may also e-mail your
answers to [email protected], or fax them to us at 1-216-781-0331. If you have any questions,
please contact the Instruction Department.
1. In Python, you can write a print statement that includes two or more expressions separated
by ____.
1) periods 3) colons
2) commas 4) semicolons
2. In carrying out the instructions of any algorithm, the computing agent starts with some given
information (known as ____).
1) data 3) input
2) variables 4) output
3. In the modern world of computers, information is also commonly referred to as ____.
1) data 3) input
2) bits 4) records
4. Python is a(n) ____ language.
1) functional 3) interpreted
2) assembly 4) compiled
5. In a computer, the ____ devices include a keyboard, a mouse, and a microphone.
1) memory 3) input
2) CPU 4) output
6. ____ programming languages resemble English and allow the author to express algorithms in a
form that other people can understand.
1) Assembly 3) Low-level
2) Interpreted 4) High-level
7. An algorithm consists of a(n) ____ number of instructions.
1) finite 3) predefined
2) infinite 4) undefined
8. To quit the Python shell, you can either select the window’s close box or press the ____ key
combination.
1) Control+C 3) Control+Z
2) Control+D 4) Control+X
9. A ____ takes a set of machine language instructions as input and loads them into the
appropriate memory locations.
1) compiler 3) loader
2) linker 4) interpreter
10. The escape sequence ____ is the newline character.
1) \l 3) \eof
2) \n 4) \eol
11. In carrying out the instructions of any algorithm, the computing agent transforms some given
information according to well-defined rules, and produces new information, known as ____.
1) data 3) input
2) variables 4) output
18
12. ____ consists of the physical devices required to execute algorithms.
1) Firmware 3) I/O
2) Hardware 4) Processors
13. A(n) ____ function is a function with the same name as the data type to which it converts.
1) semantic 3) casting
2) abstraction 4) type conversion
14. In Python, ____ is the exponentiation operator.
1) ^ 3) %
2) & 4) **
15. ____ was considered ideal for numerical and scientific applications.
1) COBOL 3) LISP
2) Machine code 4) FORTRAN
16. CDs and DVDs are an example of ____ storage media.
1) semiconductor 3) optical
2) magnetic 4) primary
17. Computers can communicate with the external world through various ____ that connect them
to networks and to other devices such as handheld music players and digital cameras.
1) facilities 3) racks
2) ports 4) slots
18. In the ____ phase of the waterfall model, the programmers determine how the program will do
its task.
1) customer request 3) design
2) analysis 4) maintenance
19. ____ developed a system of logic which consisted of a pair of values, TRUE and FALSE, and a
set of three primitive operations on these values, AND, OR, and NOT.
1) George Boole 3) Herman Hollerith
2) Joseph Jacquard 4) Charles Babbage
20. ____ is the set of algorithms, represented as programs in particular programming languages.
1) Freeware 3) Software
2) Shareware 4) Dataset
21. ____ is a character set.
1) Unicode 3) Waterfall
2) STX 4) Bytecode
22. ____ is the set of rules for constructing well-formed expressions or sentences in a language.
1) Grammar 3) Semantics
2) Syntax 4) Logic
23. Flash memory sticks are an example of ____ storage media.
1) semiconductor 3) optical
2) magnetic 4) primary
19
24. A(n) ____ program produces the expected output for any legitimate input.
1) correct 3) efficient
2) appropriate 4) logical
25. In programming, a ____ consists of a set of values and a set of operations that can be
performed on those values.
1) class 3) data type
2) data structure 4) literal
26. In its early days, ____ was used primarily for laboratory experiments in an area of research
known as artificial intelligence.
1) COBOL 3) LISP
2) Machine code 4) FORTRAN
END OF EXAM
2
Chapter 3 - Control Statements
LESSON 9302C
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Lesson Assignment
Chapter Notes
Overview
Chapter 3 describes the different control statements available in Python. You learn how
to write for and while loops, and how to use them to repeat actions, traverse lists,
count up and down, and generate random numbers. Selection statements are also
covered, including one-way selection statements (if), two-way selection statements
(if-else), and multi-way selection statements.
Objectives
After completing this chapter, you will be able to:
Write a loop to repeat a sequence of actions a fixed number of times
Write a loop to traverse the sequence of characters in a string
Write a loop that counts down and a loop that counts up
Write an entry-controlled loop that halts when a condition becomes false
Use selection statements to make choices in a program
Construct appropriate conditions for condition-controlled loops and selection statements
Use logical operators to construct compound Boolean expressions
3
Use a selection statement and a break statement to exit a loop that is not entry-
controlled
Topic Tips
Definite Iteration: The for Loop
Topic Tip For more information on Python loops, visit:
http://en.wikibooks.org/wiki/Python_Programming/Loops.
Formatting Text for Output
Topic Tip You can find some useful information about string formatting operations in
Python at: http://docs.python.org/lib/typesseq-strings.html.
Quick Quiz 1
1. What is an iteration?
2. True or False: When two arguments are supplied to xrange, the count ranges from the
first argument to the second argument minus 1.
3. True or False: The third argument of the xrange function specifies the upper bound of
the count.
4. The total number of data characters and additional spaces for a given datum in a
formatted string is called its ____________________.
Selection: if and if-else Statements
Topic Tip For more information on loops and conditionals in Python, read:
www.sthurlow.com/python/lesson04/.
Topic Tip For more information on short-circuit evaluation, read:
http://en.wikipedia.org/wiki/Short-circuit_evaluation.
Quick Quiz 2
4
1. In Python, ____________________ literals can be written in several ways, but most
programmers prefer the use of the standard values True and False.
2. What is a two-way selection statement?
3. True or False: Python includes all three Boolean or logical operators, and, or, and
xor.
4. True or False: There are times when short-circuit evaluation is advantageous.
Conditional Iteration: The while Loop
Topic Tip For more information on the break statement, read:
http://docs.python.org/ref/break.html.
Topic Tip Besides the break statement, continue statements are also useful in loops.
For more information, visit: http://docs.python.org/ref/continue.html.
Topic Tip For more information on random number generators, visit:
http://en.wikipedia.org/wiki/Random_number_generator.
Case Study: Approximating Square Roots
Topic Tip
For more information on Newton’s and other square root approximation
algorithms, visit:
http://en.wikipedia.org/wiki/Methods_of_computing_square_roots.
Quick Quiz 3
1. What is conditional iteration?
2. The while loop is also called a(n) ____________________ loop, because its condition
is tested at the top of the loop.
3. True or False: A while loop cannot be used for a count-controlled loop.
4. A(n) ____________________ statement causes an exit from the loop that contains it.
Additional Resources
5
1. Python Programming/Loops:
http://en.wikibooks.org/wiki/Python_Programming/Loops
2. Python Tutorial: More Control Flow Tools:
http://docs.python.org/tut/node6.html
3. A Beginner’s Python Tutorial: Loops and Conditionals:
www.sthurlow.com/python/lesson04/
4. The break Statement:
http://docs.python.org/ref/break.html
Key Terms
assignment operator: The symbol -, which is used to give a value to a variable.
augmented assignment: An assignment operation that performs a designated
operation, such as addition, before storing the result in a variable.
Boolean expression: An expression whose value is either true or false. See also
compound Boolean expression and simple Boolean expression.
compound Boolean expression: Refers to the complete expression when logical
connectives and negation are used to generate Boolean values. See also Boolean
expression and simple Boolean expression.
concatenation: An operation in which the contents of one sequence are placed after the
contents of another sequence.
conjunction: The connection of two Boolean expressions using the logical operator
and, returning false if at least one of the expressions is false or true if they are both true.
continuation condition: A Boolean expression that is checked to determine whether or
not to continue iterating within a loop. If this expression is True, iteration continues.
control statement: A statement that allows the computer to repeat or select an action.
count-controlled loop: A loop that stops when a counter variable reaches a specified
limit.
data validation: The process of examining data prior to its use in a program.
definite iteration: The process of repeating a given action a preset number of times.
extended if statement: Nested selection in which additional if-else statements are used
in the else option. See also nested if statement.
for loop: A structured loop used to traverse a sequence.
format string: A special syntax within a string that allows the programmer to specify
the number of columns within which data are placed in a string.
if-else statement: A selection statement that allows a program to perform alternative
actions based on a condition.
indefinite iteration: The process of repeating a given action until a condition stops the
repetition.
infinite loop: A loop in which the controlling condition is not changed in such a
manner to allow the loop to terminate.
logical operator: Either of the logical connective operators and, or, or not.
logical structure: The organization of the components in a data structure, independent
of their organization in computer memory.
6
loop(s): A type of statement that repeatedly executes a set of statements. See also
control statements.
loop body: The action(s) performed on each iteration through a loop.
loop header: Information at the beginning of a loop that includes the conditions for
continuing the iteration process.
minimum spanning forest: The set of all minimum spanning trees in a graph.
off-by-one error: Usually seen with loops, this error shows up as a result that is one
less or one greater than the expected value.
relational operator: An operator used for comparison of data items of the same type.
selection: The process by which a method or a variable of an instance or a class is
accessed.
selection statement: A control statement that selects some particular logical path based
on the value of an expression. Also referred to as a conditional statement.
sentinel value (sentinel): A special value that indicates the end of a set of data or of a
process.
sequence: A type of collection in which each item but the first has a unique predecessor
and each item but the last has a unique successor.
short-circuit evaluation: The process by which a compound Boolean expression halts
evaluation and returns the value of the first subexpression that evaluates to true, in the
case of or, or false, in the case of and.
simple Boolean expression: An expression in which two numbers or variable values
are compared using a single relational operator. See also Boolean expression and
compound Boolean expression.
step value: The amount by which a counter is incremented or decremented in a count-
controlled loop.
structured programming: Programming that parallels a solution to a problem
achieved by top-down implementation. See also stepwise refinement and top-down
design.
termination condition: A Boolean expression that is checked to determine whether or
not to stop iterating within a loop. If this expression is True, iteration stops.
truth table: A means of listing all of the possible values of a Boolean expression.
while loop(s): A pretest loop that examines a Boolean expression before causing a
statement to be executed.
7
Python Lesson 9302C Exam
Please complete the following exam. You may use the electronic grading system for quicker
response. Simply log on to www.study-electronics.com and enter your credentials. Once the
exam has been submitted, your results will be returned within 72 hours. You may also e-mail
your answers to [email protected], or fax them to us at 1-216-781-0331. If you have any
questions, please contact the Instruction Department.
Multiple Choice
Identify the choice that best completes the statement or answers the question.
1. The ____ data type consists of only two data values—true and false.
1) digital 3) logical
2) binary 4) Boolean
2. The if-else statement is also called a ____ selection statement.
1) multi-way 3) one-way
2) Boolean 4) two-way
3. A ____ must follow the else in an if-else statement.
1) : 3) ,
2) ; 4) {
4. The condition in the if-else statement ____ be a Boolean expression.
1) may 3) must
2) should 4) must not
5. In ____ format, numbers and other information are aligned in columns that can be either left-
justified or right-justified.
1) range 3) column
2) tabular 4) row-order
6. "%6s" % "four" right-justifies the string by padding it with ____.
1) two spaces to its left 3) six spaces to its left
2) two spaces to its right 4) six spaces to its right
7. The first line of code in a loop is sometimes called the loop ____.
1) iteration 3) header
2) initialization 4) banner
8. The if statement is also called a ____ selection statement.
1) multi-way 3) one-way
2) Boolean 4) two-way
9. An example of conditional iteration is when a program’s input loop accepts values until the
user enters a special value or a ____ terminates the input.
1) sentinel 3) variable
2) literal 4) marker
10. In the expression (A or B), if A is true, then so is the expression, and there is no need to
evaluate B. This approach, in which evaluation stops as soon as possible, is called ____
evaluation.
1) Boolean 3) short-circuit
2) strongly-typed 4) lazy
8
11. The ____ operator returns False if and only if both of its operands are false, and returns
True otherwise.
1) and 3) not
2) or 4) xor
12. The not operator has a lower precedence than the ____ operator(s).
1) comparison 3) or
2) and 4) assignment
13. In a loop, each repetition of the action is known as a pass or a(n) ____.
1) round 3) step
2) iteration 4) cycle
14. The ____ argument of Python’s xrange and range functions specifies a step value.
1) first 3) third
2) second 4) fourth
15. What will the following loop print on the screen? for count in xrange(4):
print count,
1) 0 1 2 3 3) 3
2) 1 2 3 4 4) 4
16. ____ is the format operator.
1) & 3) ^
2) % 4) $
17. To halt a loop that appears to be hung during testing, type ____ in the terminal window or in
the IDLE shell.
1) Control+x 3) Control+c
2) Control+q 4) Control+h
18. The function ____ returns a random number from among the numbers between the two
arguments and including those numbers.
1) randgen 3) random
2) randrange 4) randint
19. The logical operators have a higher precedence than the ____ operator(s).
1) exponentiation 3) comparison
2) arithmetic negation 4) assignment
20. Python’s ____ module supports several ways to generate random numbers.
1) rnd 3) rand
2) random 4) randgen
21. The ____ comparison operator is used for equality.
1) = 3) =:
2) == 4) :=
22. In Python, a ____ ends the loop header.
1) : 3) ,
2) ; 4) ->
23. Using the ____ statement within the body of a loop will cause an exit from the loop.
1) exit 3) stop
2) break 4) continue
24. Loops that count through a range of numbers are also called ____ loops.
1) range-delimited 3) iterative
9
2) numbering 4) count-controlled
25. Errors to rule out during testing the while loop include an incorrectly initialized loop control
variable, failure to update this variable correctly within the loop, and failure to test it correctly
in the ____ condition.
1) count 3) exit
2) sentinel 4) continuation
END OF EXAM
10
Chapter 4 - Strings and Text Files
LESSON 9303C
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Chapter Notes
Overview
Chapter 4 provides an introduction to strings and text files in Python. You learn how
use and manipulate strings, including the use of some of the most useful string methods.
Next you learn to create, read from, and write to text files. Finally, you learn how to use
library functions to access and navigate a file system.
Objectives
After completing this chapter, you will be able to:
Access individual characters in a string
Retrieve a substring from a string
Search for a substring in a string
Convert a string representation of a number from one base to another base
Use string methods to manipulate strings
Open a text file for output and write strings or numbers to the file
Open a text file for input and read strings or numbers from the file
Use library functions to access and navigate a file system
Topic Tips
11
Accessing Characters and Substrings in Strings
Topic Tip For a brief introduction to text processing in Python, read:
www.ibm.com/developerworks/linux/library/l-python5.html.
Data Encryption
Topic Tip For more information about the Caesar cipher, read:
http://en.wikipedia.org/wiki/Caesar_cipher.
Quick Quiz 1
1. What is a data structure?
2. True or False: The string is an immutable data structure.
3. True or False: To extract a substring, the programmer places a semicolon (;) in the
subscript.
4. The operator ____________________ returns True if the target string is somewhere in
the search string, or False otherwise.
String Methods
Topic Tip For a complete list of the string methods available in Python, visit:
http://docs.python.org/lib/string-methods.html.
Quick Quiz 2
1. What is positional notation?
2. True or False: The octal system uses a base of 8 and the digits 0…7.
3. True or False: Each digit in the hexadecimal number is equivalent to three digits in the
binary number.
4. Unlike a function, a method is always called with a given data value called a(n)
____________________, which is placed before the method name in the call.
12
Text Files
Topic Tip For more information on file objects, read: http://docs.python.org/lib/bltin-
file-objects.html.
Case Study: Text Analysis
Topic Tip
Bottom-up testing: “An integration testing technique that tests the low-level
components first using test drivers for those components that have not yet been
developed to call the low-level components for test.”
For more information, read: http://foldoc.org/?bottom-up+testing.
Quick Quiz 3
1. Data can be output to a text file using a(n) ____________________ object.
2. True or False: You can close a file with the append method.
3. True or False: The file method write expects a string as an argument.
4. After input is finished, another call to read would return a(n)
____________________, to indicate that the end of the file has been reached.
Additional Resources
1. String Methods:
http://docs.python.org/lib/string-methods.html
2. Python String Methods:
http://python.about.com/od/pythonstandardlibrary/a/string-methods.htm
3. Caesar Cipher:
http://en.wikipedia.org/wiki/Caesar_cipher
4. Charming Python: Text Processing in Python:
www.ibm.com/developerworks/linux/library/l-python5.html
5. File Objects:
http://docs.python.org/lib/bltin-file-objects.html
Key Terms
13
ASCII character set: The American Standard Code for Information Interchange
ordering for a character set.
binary digit: A digit, either 0 or 1, in the binary number system. Program instructions
are stored in memory using a sequence of binary digits. See also bit.
bit: A binary digit.
block cipher: An encryption method that replaces characters with other characters
located in a two-dimensional grid of characters.
bottom-up implementation: A method of coding a program that starts with lower-level
modules and a test driver module.
Caesar cipher: An encryption method that replaces characters with other characters a
given distance away in the character set.
concatenation: An operation in which the contents of one sequence are placed after the
contents of another sequence.
data decryption: The process of translating encrypted data to a form that can be used.
data encryption: The process of transforming data so that others cannot use it.
data structure: A compound unit consisting of several data values.
driver: A function used to test other functions.
encryption: The process of transforming data so that others cannot use it.
file: A data structure that resides on a secondary storage medium
accessing/manipulating.
hacking: The use of clever techniques to write a program, often for the purpose of
gaining access to protected resources on networks.
index: The relative position of a component of a linear data structure or collection.
key(s): An item that is associated with a value and which is used to locate that value in
a collection.
matrix: A two-dimensional array that provides range checking and can be resized.
method(s): A chunk of code that can be treated as a unit and invoked by name. A
method is called with an object or class.
newline character: A special character (‘\n’) used to indicate the end of a line of
characters in a string or a file stream.
object: A collection of data and operations, in which the data can be accessed and
modified only by means of the operations.
overriding: The process of re-implementing a method already implemented in a
superclass.
positional notation: The type of representation used in based number systems, in
which the position of each digit denotes a power in the system’s base.
slicing: An operation that returns a subsection of a sequence, for example, a sublist or a
substring.
source program: A program written by a programmer.
subroutine: A method or a function.
substring: A string that represents a segment of another string.
text files: Files that contain characters and are readable and writable by text editors.
Continue to the next chapter for the lesson exam
14
Chapter 5 - Lists and Dictionaries
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Lesson Assignment
Chapter Notes
Overview
Chapter 5 describes lists and dictionaries. You learn to construct, use, and manipulate
lists. You also learn to define simple functions that expect parameters and return values.
Finally, you learn to construct, use, and manipulate dictionaries.
Objectives
After completing this chapter, you will be able to:
Construct lists and access items in those lists
Use methods to manipulate lists
Perform traversals of lists to process items in the lists
Define simple functions that expect parameters and return values
Construct dictionaries and access entries in those dictionaries
Use methods to manipulate dictionaries
Decide whether a list or a dictionary is an appropriate data structure for a given
application
15
Topic Tips
Lists
Topic Tip For more on Python lists, visit:
http://diveintopython.org/native_data_types/lists.html.
Topic Tip In Python, lists can be used as stacks and as queues. For more information, read:
http://docs.python.org/tut/node7.html.
Topic Tip
“Assigning a tuple to a several different variables is called tuple unpacking,
while assigning multiple values to a tuple in one variable is called tuple packing.
When unpacking a tuple, or performing multiple assignment, you must have the
same number of variables being assigned to as values being assigned.”
Reference: http://en.wikibooks.org/wiki/Python_Programming/Tuples.
Quick Quiz 1
1. What is a list in Python?
2. True or False: The is operator can be used to detect the presence or absence of a given
element in a list.
3. True or False: A list is immutable.
4. What is a tuple?
Defining Simple Functions
Topic Tip
Python allows the programmer to provide default parameters in the header of a
function definition. For more information, read:
http://docs.python.org/ref/function.html
Quick Quiz 2
1. Why would you want to define your own functions?
2. True or False: The function’s header contains the function’s name and a parenthesized
list of argument names.
16
3. The header of a function consists of the reserved word ____________________,
followed by the function’s name, followed by a parenthesized list of parameters and a
colon.
4. A(n) ____________________ function usually tests its argument for the presence or
absence of some property.
Dictionaries
Topic Tip
Here are some useful resources with more information about Python dictionaries:
http://diveintopython.org/getting_to_know_python/dictionaries.html
www.developer.com/article.php/630721
http://en.wikibooks.org/wiki/Python_Programming/Dictionaries
Topic Tip
Besides lists, tuples, and dictionaries, Python also includes a data type for sets. For
more information, read:
http://docs.python.org/tut/node7.html#SECTION007400000000000000000.
Case Study: Nondirective Psychotherapy
Topic Tip
Nondirective psychotherapy is also called client-centered or person-centered
psychotherapy. For more information, view the Britannica Online Encyclopedia
entry on the subject:
http://www.britannica.com/EBchecked/topic/417641/nondirective-
psychotherapy.
Quick Quiz 3
1. What is a dictionary?
2. True or False: A dictionary associates a set of indexes with data values.
3. True or False: [] is an empty dictionary.
4. When working with dictionaries, if the existence of a key is uncertain, the programmer
can test for it using the dictionary method has_key, but a far easier strategy is to use
the method ____________________.
Topic Tip A dictionary is like a hash in Perl, a Hashtable in Java, and an instance of the
Scripting.Dictionary object in Visual Basic.
17
Additional Resources
1. Python Tutorial: Data Structures:
http://docs.python.org/tut/node7.html
2. Dive Into Python: Introducing Lists:
http://diveintopython.org/native_data_types/lists.html
3. Python Programming/Tuples:
http://en.wikibooks.org/wiki/Python_Programming/Tuples
4. Python Tutorial: Function Definitions:
http://docs.python.org/ref/function.html
5. Python Programming/Dictionaries:
http://en.wikibooks.org/wiki/Python_Programming/Dictionaries
Key Terms
alias: A situation in which two or more names in a program can refer to the same
memory location. An alias can cause subtle side effects.
assignment operator: The symbol -, which is used to give a value to a variable.
association: A pair of items consisting of a key and a value.
binary digit: A digit, either 0 or 1, in the binary number system. Program instructions
are stored in memory using a sequence of binary digits. See also bit.
concatenation: An operation in which the contents of one sequence are placed after the
contents of another sequence.
conjunction: The connection of two Boolean expressions using the logical operator
and, returning false if at least one of the expressions is false or true if they are both true.
count-controlled loop: A loop that stops when a counter variable reaches a specified
limit.
dictionary: A data structure that allows the programmer to access items by specifying
key values.
element: A value that is stored in an array or a collection.
function(s): A chunk of code that can be treated as a unit and called to perform a task.
function heading: The portion of a function implementation containing the function’s
name and parameter names.
grammar: The set of rules for constructing sentences in a language.
hacking: The use of clever techniques to write a program, often for the purpose of
gaining access to protected resources on networks.
identity: The property of an object that it is the same thing at different points in time,
even though the values of its attributes might change.
index: The relative position of a component of a linear data structure or collection.
key(s): An item that is associated with a value and which is used to locate that value in
a collection.
18
logical structure: The organization of the components in a data structure, independent
of their organization in computer memory.
loop(s): A type of statement that repeatedly executes a set of statements. See also
control statements.
mutator: A method used to change the value of an attribute of an object.
natural ordering: The placement of data items relative to each other by some internal
criteria, such as numeric value or alphabetical value.
None value: A special value that indicates that no object can be accessed.
object identity: The property of an object that it is the same thing at different points in
time, even though the values of its attributes might change.
pop: The operation that removes an element from a Python list or stack.
side effect: A change in a variable that is the result of some action taken in a program,
usually from within a method.
state: The set of all the values of the variables of a program at any point during its
execution.
structural equivalence: A criterion of equality between two distinct objects in which
one or more of their attributes are equal.
tuple: A linear, immutable collection.
value: An item that is associated with a key and is located by a key in a collection.
19
Python Lesson 9303C Exam
Please complete the following exam. You may use the electronic grading system for quicker
response. Simply log on to www.study-electronics.com and enter your credentials. Once the
exam has been submitted, your results will be returned within 72 hours. You may also e-mail
your answers to [email protected], or fax them to us at 1-216-781-0331. If you have any
questions, please contact the Instruction Department.
Multiple Choice
Identify the choice that best completes the statement or answers the question.
1. Python’s ____ operator can be used to test for object identity.
1) in 3) equals
2) is 4) refers
2. The decimal number 8 is expressed as ____ in binary.
1) 100 3) 111
2) 110 4) 1000
3. The string method ____ can be used to obtain a list of the words contained in an input string.
1) substring 3) words
2) split 4) strip
4. ____ is not a valid list in Python.
1) [] 3) [2:4]
2) ['apples','oranges'] 4) [[5, 9], [541, 78]]
5. If the existence of a key is uncertain, the programmer can test for it using the dictionary method
____.
1) has_key 3) hasKey
2) haskey 4) has-key
6. The decimal number 6 is expressed as ____ in binary.
1) 100 3) 111
2) 110 4) 1000
7. To extract a substring, the programmer places a ____ in the subscript.
1) . 3) ;
2) : 4) ,
8. In Python, the values of most data types can be converted to strings by using the ____ function.
1) convert 3) str
2) toString 4) string
9. You can use the dictionary method ____ to remove all the keys in the dictionary.
1) clear() 3) remove()
2) reset() 4) zero()
10. The ____ file system function returns the path of the current working directory.
1) chdir 3) listdir
2) getcwd 4) mkdir
11. Mutable objects have some methods devoted entirely to modifying the internal state of the
object. Such methods are called ____.
1) accessors 3) modifiers
2) mutators 4) Procedures
20
12. ____ returns the number of elements in the list.
1) len(L) 3) length(L)
2) siz(L) 4) size(L)
13. The ____ function is the inverse of the ord function.
1) dro 3) chr
2) rord 4) in
14. The L.____(aList) method of the list type adds the elements of L to the end of aList.
1) join 3) extend
2) concatenate 4) append
15. You indicate a tuple literal in Python by enclosing its elements in ____.
1) () 3) <>
2) [] 4) {}
16. ____ is an example of an empty dictionary.
1) [] 3) ()
2) {} 4) <>
17. Python’s open function, which expects a file pathname and a ____ string as arguments, opens
a connection to the file on disk and returns a file object.
1) reference 3) pattern
2) mode 4) bit
18. When using the subscript operator, the integer expression is also called a(n) ____.
1) suffix 3) index
2) step 4) iterator
19. The L.____(index) method of the list type removes and returns the element at index.
1) pop 3) get
2) remove 4) append
20. The ____ method of the list type adds an element to the end of the list.
1) addToEnd 3) atEnd
2) addLast 4) append
21. In Python, a ____ associates a set of keys with data values.
1) string 3) list
2) tuple 4) dictionary
22. The string method ____ returns a string that is the concatenation of the strings in the sequence.
1) center 3) concatenate
2) split 4) join
23. The string method ____ returns a copy of the string converted to lowercase.
1) lower 3) lowerCase
2) toLower 4) toLowerCase
24. A ____ allows the programmer to manipulate a sequence of data values of any types.
1) list 3) data structure
2) string 4) dictionary
25. The ____ file system function creates a new directory with the given name, and places it in the
current working directory.
1) chdir 3) listdir
2) getcwd 4) mkdir
END OF EXAM
21
Chapter 6 - Design with Functions
LESSON 9304C
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Lesson Assignment
Chapter Notes
Overview
Chapter 6 describes the role of functions in structuring code in a program. You learn to
employ top-down design to assign tasks to functions. Through several examples, you
learn to use and define functions, including the use of optional parameters. Advanced
topics like recursion, namespaces, and higher-order functions are covered too.
Objectives
After completing this chapter, you will be able to:
Explain why functions are useful in structuring code in a program
Employ top-down design to assign tasks to functions
Define a recursive function
Explain the use of the namespace in a program and exploit it effectively
Define a function with required and optional parameters
Use higher-order functions for mapping, filtering, and reducing
22
Topic Tips
Functions as Abstraction Mechanisms
Topic Tip
“In computer science, abstraction is a mechanism and practice to reduce and
factor out details so that one can focus on a few concepts at a time.”
Reference: http://en.wikipedia.org/wiki/Abstraction_(computer_science).
Problem Solving with Top-Down Design
Topic Tip “Top-down design was promoted in the 1970s by IBM researcher Harlan Mills
and Niklaus Wirth.” Reference: http://en.wikipedia.org/wiki/Top-down.
Quick Quiz 1
1. What is an abstraction?
2. True or False: Functions serve as abstraction mechanisms is by hiding complicated
details.
3. True or False: The individual problems that make up a class of problems are known as
problem variations.
4. What is top-down design?
Design with Recursive Functions
Topic Tip For more information on recursion in mathematics and computer science, read:
http://en.wikipedia.org/wiki/Recursion.
Topic Tip
“In computer science, tail recursion (or tail-end recursion) is a special case of
recursion in which the last operation of the function is a recursive call. Such
recursions can be easily transformed to iterations. Replacing recursion with
iteration, manually or automatically, can drastically decrease the amount of stack
space used and improve efficiency. This technique is commonly used with
functional programming languages, where the declarative approach and explicit
handling of state promote the use of recursive functions that would otherwise
rapidly fill the call stack.”
Reference: http://en.wikipedia.org/wiki/Tail_recursion
23
Topic Tip
While the depth of indirect recursion may vary, indirect recursion requires the
same attention to base cases as direct recursion. For more information, visit:
www.cs.sfu.ca/~tamaras/recursion/Direct_vs_Indirect.html.
Quick Quiz 2
1. What is a recursive function?
2. A recursive ____________________ consists of equations that state what a value is for
one or more base cases and one or more recursive cases.
3. True or False: Inefficient recursion arises when the programmer fails to specify the base
case or to reduce the size of the problem in a way that terminates the recursive process.
4. What is a stack frame?
Managing a Program’s Namespace
Topic Tip
Python has two built-in functions, locals and globals, which provide
dictionary-based access to local and global variables. For more information,
visit: www.faqs.org/docs/diveintopython/dialect_locals.html.
Topic Tip
A note on default arguments: “The default value is evaluated only once. This
makes a difference when the default is a mutable object such as a list, dictionary,
or instances of most classes. For example, the following function accumulates
the arguments passed to it on subsequent calls.”
Reference: http://docs.python.org/tut/node6.html
Higher-Order Functions (Advanced Topic)
Topic Tip
Python supports multiple programming paradigms (primarily object oriented,
imperative, and functional). For more information on how to use Python as a
functional programming language, see the second reference listed below.
References:
http://en.wikipedia.org/wiki/Python_(programming_language) and
http://gnosis.cx/publish/programming/charming_python_13.html
24
Topic Tip
“In computer programming, a branch table (sometimes known as a jump table) is
a term used to describe an efficient method of transferring program control
(branching) to another part of a program (or a different program that may have
been dynamically loaded) using a table of branch instructions. The branch table
construction is commonly used when programming in assembly language but
may also be generated by a compiler.”
Reference: http://en.wikipedia.org/wiki/Branch_table
Quick Quiz 3
1. What is a program’s namespace?
2. True or False: When module variables are introduced in a program, they are
immediately given a value.
3. True or False: In a program, the context that gives a name a meaning is called its
lifetime.
4. Explain what the following statement means: “In Python, functions can be treated as
first-class data objects.”
Additional Resources
1. Recursion:
http://en.wikipedia.org/wiki/Recursion
2. Python Scopes and Name Spaces:
www.network-theory.co.uk/docs/pytut/PythonScopesandNameSpaces.html
3. Default Argument Values:
http://docs.python.org/tut/node6.html#SECTION006710000000000000000
4. Functional Programming in Python:
http://gnosis.cx/publish/programming/charming_python_13.html
Key Terms
abstraction: A simplified view of a task or data structure that ignores complex detail.
activation record: An area of computer memory that keeps track of a function or
method call’s parameters, local values, return value, and the caller’s return address.
analysis: The phase of the software life cycle in which the programmer describes what
the program will do.
anonymous function: A function without a name, constructed in Python using lambda.
25
base case: The condition in a recursive algorithm that is tested to halt the recursive
process.
call: Any reference to a function or method by an executable statement. Also referred to
as invoke.
call stack: The trace of function or method calls that appears when Python raises an
exception during program execution.
compiler: A computer program that automatically converts instructions in a high-level
language to byte code or machine language.
conjunction: The connection of two Boolean expressions using the logical operator
and, returning false if at least one of the expressions is false or true if they are both true.
data validation: The process of examining data prior to its use in a program.
debugging: The process of eliminating errors, or bugs, from a program.
default parameter: Also called a default argument. A special type of parameter that is
automatically given a value if the caller does not supply one.
filtering: The successive application of a Boolean function to a list of arguments that
returns a list of the arguments that make this function return True.
first-class data objects: Data objects that can be passed as arguments to functions and
returned as their values.
general method: A method that solves a class of problems, not just one individual
problem.
grammar: The set of rules for constructing sentences in a language.
higher-order function: A function that expects another function as an argument and/or
returns another function as a value.
indirect recursion: A recursive process that results when one function calls another,
which results at some point in a second call to the first function.
infinite recursion: In a running program, the state that occurs when a recursive
function cannot reach a stopping state.
jump table: A dictionary that associates command names with functions that are
invoked when those functions are looked up in the table.
lambda: The mechanism by which an anonymous function is created.
lifetime: The time during which a data object, function call, or method call exists.
mapping: The successive application of a function to a list of arguments that returns a
list of results.
method header: The portion of a method implementation containing the method’s
name and parameter names.
namespace(s): The set of all of a program’s variables and their values.
path: A sequence of edges that allows one vertex to be reached from another.
predicate: A function that returns a Boolean value.
prefix form: The form of an expression in which the operator precedes its operands.
problem decomposition: The process of breaking a problem into subproblems.
problem instance: An individual problem that belongs to a class of problems.
recursion: The process of a subprogram calling itself. A clearly defined stopping state
must exist.
recursive call: The call of a function that already has a call waiting in the current chain
of function calls.
recursive definition: A set of statements in which at least one statement is defined in
terms of itself.
recursive design: The process of decomposing a problem into subproblems of exactly
the same form that can be solved by the same algorithm.
26
recursive function: A function that calls itself.
recursive step: A step in the recursive process that solves a similar problem of smaller
size and eventually leads to a termination of the process.
reducing: The application of a function to a list of its arguments to produce a single
value.
reserved words: Words that have predefined meanings that cannot be changed.
responsibility-driven design: The assignment of roles and responsibilities to different
actors in a program.
root directory: The top-level directory in a file system.
run-time stack: An area of computer memory reserved for local variables and
parameters of method calls.
run-time system: Software that supports the execution of a program.
scope: The area of program text in which the value of a variable is visible.
stepwise refinement: The process of repeatedly subdividing tasks into subtasks until
each subtask is easily accomplished. See also structured programming and top-down
design.
structure chart: A graphical method of indicating the relationship between modules
when designing the solution to a problem.
temporary variable: A variable that is introduced in the body of a function or method
for the use of that subroutine only.
top-down design: A method for coding by which the programmer starts with a top-
level task and implements subtasks. Each subtask is then subdivided into smaller
subtasks. This process is repeated until each remaining subtask is easily coded.
tuple: A linear, immutable collection.
27
Python Lesson 9304C Exam
Please complete the following exam. You may use the electronic grading system for quicker
response. Simply log on to www.study-electronics.com and enter your credentials. Once the
exam has been submitted, your results will be returned within 72 hours. You may also e-mail
your answers to [email protected], or fax them to us at 1-216-781-0331. If you have any
questions, please contact the Instruction Department.
Multiple Choice
Identify the choice that best completes the statement or answers the question.
1. A ____ is the period of time during program execution when the variable has memory storage
associated with it.
1) name’s scope 3) module
2) namespace 4) variable’s lifetime
2. In Python, functions can be treated as ____. This means that they can be assigned to variables
(as they are when they are defined), passed as arguments to other functions, returned as the
values of other functions, and stored in data structures such as lists and dictionaries.
1) abstract entities 3) first-class data objects
2) classes 4) modules
3. In the case of infinite recursion, the stack frames are added until the PVM ____.
1) runs out of memory 3) notes the anomaly
2) is halted by the user 4) iterates 210
times
4. When working with file systems, you can use the module variable ____ to obtain the
appropriate slash symbol (/ or \) on the current file system.
1) os.slash 3) os.sep
2) os.div 4) os.path
5. If designed properly, a ____’s code captures an algorithm as a general method for solving a
class of problems.
1) module 3) literal
2) function 4) script
6. Separating the logic of choosing a task from the process of carrying out a task makes the
program more ____.
1) maintainable 3) elegant
2) abstract 4) efficient
7. In a recursive function, the ____ case determines whether to stop or to continue with another
recursive step.
1) exception 3) base
2) exit 4) selection
8. The individual problems that make up a class of problems are known as problem ____.
1) indexes 3) instances
2) items 4) modules
28
9. On a UNIX-based file system, the path to a given file or directory in the system is a string that
starts with the ____ symbol, followed by the names of the directories traversed to reach the file
or directory.
1) \ 3) ~
2) / 4) %
10. In a computer program, ____ can enforce a division of labor.
1) modules 3) functions
2) literals 4) algorithms
11. A ____ behaves like a variable and is introduced in a function or method header.
1) module 3) parameter name
2) namespace 4) class
12. A ____ is a dictionary of functions keyed by command names.
1) jump table 3) stack frame
2) namespace 4) module
13. A(n) ____ function separates the task of transforming each data value from the logic of
accumulating the results.
1) higher-order 3) abstract
2) recursive 4) top-down
14. When ____ are introduced in a program, they are immediately given a value.
1) arguments 3) parameters
2) namespaces 4) module variables
15. In the ____ process, we take a list of values and repeatedly apply a function to accumulate a
single data value.
1) abstraction 3) filtering
2) mapping 4) reducing
16. A ____ function is a function that calls itself.
1) unitary 3) self-calling
2) recursive 4) constructor
17. One way in which functions serve as abstraction mechanisms is by ____.
1) using a bottom-up approach to design
2) hiding complicated details
3) providing a docstring to help the programmer
4) providing white-box functionality
18. In Python, a ____ is the area of program text in which the name refers to a given value.
1) name’s scope 3) module
2) namespace 4) variable’s lifetime
19. A(n) ____ consists of equations that state what a value is for one or more base cases and one or
more recursive cases.
1) recursive function 3) induction definition
2) recursive definition 4) stepwise function
29
20. ____ design starts with a global view of the entire problem and breaks the problem into
smaller, more manageable subproblems.
1) Top-down 3) White-box
2) Bottom-up 4) Object-oriented
21. One way in which functions serve as abstraction mechanisms is by ____.
1) eliminating redundant, or repetitious, code
2) assigning a name to a group of statements
3) providing a docstring to help the programmer
4) providing white-box functionality
22. In ____ design, you decompose a complex problem into smaller problems of exactly the same
form.
1) top-down 3) modular
2) bottom-up 4) recursive
23. A(n) ____ is a general method for solving a class of problems.
1) class 3) module
2) function 4) algorithm
24. At the top of a file-system tree is the ____.
1) root directory 3) stack frame
2) master boot record 4) path
25. The first and second numbers in the Fibonacci sequence are ____, respectively.
1) 0 and 0 3) 1 and 1
2) 0 and 1 4) 1 and 2
END OF EXAM
30
Chapter 7 - Simple Graphics and Image Processing
LESSON 9305C
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Lesson Assignment
Chapter Notes
Overview
Chapter 7 introduces simple graphics and image processing with Python. Some basic
concepts, like the RGB system, analog and digital information, and sampling, are
introduced. You learn to work with graphics through many examples using two non-
standard, open-source modules: turtlegraphics and images.
Objectives
After completing this chapter, you will be able to:
Use the concepts of object-based programming—classes, objects, and methods—to
solve a problem
Develop algorithms that use simple graphics operations to draw two-dimensional shapes
Use the RGB system to create colors in graphics applications and modify pixels in
images
Develop recursive algorithms to draw recursive shapes
Write a nested loop to process a two-dimensional grid
31
Develop algorithms to perform simple transformations of images, such as conversion of
color to grayscale
Topic Tips
Simple Graphics
Topic Tip
In addition to turtlegraphics, the turtle module provides turtle graphics
primitives, in both object-oriented and procedure-oriented ways. For more
information, visit: www.python.org/doc/2.3/lib/module-turtle.html.
Topic Tip
You may find it useful to experiment with Logo before using the
turtlegraphics module. For an online Turtle Logo Applet, visit:
www.mathsnet.net/logo/turtlelogo/index.html.
Quick Quiz 1
1. What is a Turtle graphics toolkit?
2. The process of creating an object is called ____________________.
3. True or False: Many graphics applications use Turtle graphics, or the drawing of simple
two-dimensional shapes, such as rectangles, triangles, and circles.
4. In the RGB system, each color component can range from 0 through
____________________.
Case Study: Recursive Patterns in Fractals
Topic Tip
“A fractal is generally a rough or fragmented geometric shape that can be split
into parts, each of which is (at least approximately) a reduced-size copy of the
whole, a property called self-similarity. The term was coined by Benoît
Mandelbrot in 1975 and was derived from the Latin fractus meaning broken or
fractured.”
Reference: http://en.wikipedia.org/wiki/Fractal
Quick Quiz 2
1. What is a fractal?
32
2. True or False: A fractal object appears geometric, and can be described with ordinary
Euclidean geometry.
3. True or False: One example of a fractal curve is the c-curve.
4. In Python, the definition of an auxiliary function can be ____________________ within
the definition of another function.
Image Processing
Topic Tip
“Digital image processing is the use of computer algorithms to perform image
processing on digital images.” For more information, visit:
http://en.wikipedia.org/wiki/Digital_image_processing.
Quick Quiz 3
1. Computers use digital information, which consists of ____________________ values,
such as individual integers, characters of text, or bits in a bit string.
2. True or False: GIF stands for Graphic Interchange Format.
3. Many image-processing algorithms use a(n) ____________________ loop structure to
traverse a two-dimensional grid of pixels.
4. A pixel’s RGB values are stored in a(n) ____________________.
Additional Resources
1. Online Logo Turtle Applet:
www.mathsnet.net/logo/turtlelogo/index.html
2. Fractal:
http://en.wikipedia.org/wiki/Fractal
3. Digital Image Processing:
http://en.wikipedia.org/wiki/Digital_image_processing
4. Image Processing with Python SIG:
www.python.org/community/sigs/current/image-sig/
Key Terms
c-curve: A fractal shape that resembles the letter C.
33
constructor: A method that is run when an object is instantiated, usually to initialize
that object’s instance variables. This method is named _init_ in Python.
coordinate system: A grid that allows a programmer to specify positions of points in a
plane or of pixels on a computer screen.
fractal geometry: A theory of shapes that are reflected in various phenomena, such as
coastlines, water flow, and price fluctuations.
fractal object: A type of mathematical object that maintains self-sameness when
viewed at greater levels of detail.
instance: A computational object bearing the attributes and behavior specified by a
class.
instantiation: The process of creating a new object or instance of a class.
interface: A formal statement of how communication occurs between the user of a
module (class or method) and its implementer.
lambda: The mechanism by which an anonymous function is created.
linear: An increase of work or memory in direct proportion to the size of a problem.
megabyte: Shorthand for approximately 1 million bytes.
method header: The portion of a method implementation containing the method’s
name and parameter names.
nested loop: A loop as one of the statements in the body of another loop.
object-based programming: The construction of software systems that use objects.
origin: The point (0,0) in a coordinate system.
pixel(s): A picture element or dot of color used to display images on a computer screen.
screen coordinate system: A coordinate system used by most programming languages
in which the origin is in the upper-left corner of the screen, window, or panel, and the y
values increase toward the bottom of the drawing area.
turtle graphics: A set of methods that manipulate a pen in a graphics window.
vector: A one-dimensional array that supports resizing, insertions, and removals.
vertex: A point or node in a graph.
34
Python Lesson 9305C Exam
Please complete the following exam. You may use the electronic grading system for quicker
response. Simply log on to www.study-electronics.com and enter your credentials. Once the
exam has been submitted, your results will be returned within 72 hours. You may also e-mail
your answers to [email protected], or fax them to us at 1-216-781-0331. If you have any
questions, please contact the Instruction Department.
Multiple Choice
Identify the choice that best completes the statement or answers the question.
1. The Turtle() method of the Turtle class creates a new Turtle object and opens its
window. The window’s drawing area is ____.
1) 50 pixels wide and 50 pixels high 3) 150 pixels wide and 150 pixels high
2) 100 pixels wide and 100 pixels high 4) 200 pixels wide and 200 pixels high
2. The method ____ of the Image class returns a tuple of the RGB values at the given
coordinates.
1) getValue 3) getRGB
2) getColor 4) getPixel
3. The process of creating an object is called ____.
1) definition 3) creation
2) initialization 4) instantiation
4. Many graphics applications use ____ graphics, or the drawing of simple two-dimensional
shapes, such as rectangles, triangles, and circles.
1) vector 3) RGB
2) turtle 4) fractal
5. The types of objects are called ____.
1) classes 3) datums
2) instances 4) structures
6. ____ is the discipline that underlies the representation and display of geometric shapes in two-
and three-dimensional space.
1) Image Processing 3) Multimedia
2) Vision 4) Graphics
7. ____ devices measure discrete color values at distinct points on a two-dimensional grid.
1) Euclidean 3) Digitalizing
2) Conversion 4) Sampling
8. The RGB value of the blue color is ____.
1) (0, 0, 0) 3) (255, 0, 0)
2) (0, 0, 255) 4) (255, 255, 255)
9. ____ are highly repetitive or recursive patterns.
1) Vectors 3) Euclideans
2) Fractals 4) Turtles
35
10. ____ removes the full colors of an image to uncover the outlines of the objects represented in
the image.
1) Pixilation 3) Edge detection
2) Blurring 4) Image processing
11. The ____ class represents an image as a two-dimensional grid of RGB values.
1) RGB 3) Vector
2) Image 4) Bitmap
12. The ____ method of the Turtle class, moves the turtle to the center of the graphics window,
without drawing any line.
1) home() 3) reset()
2) center() 4) zero()
13. The total number of bits needed to represent a distinct color value in the RGB system is ____.
1) 8 3) 24
2) 16 4) 48
14. ____ information contains a continuous range of values.
1) Discrete 3) Analog
2) Digital 4) Euclidean
15. The set of methods of a given class of objects make up its ____.
1) abstraction 3) signature
2) interface 4) semantics
16. Turtle graphics were originally developed as part of the children’s programming language
____, created by Seymour Papert and his colleagues at MIT in the late 1960s.
1) FORTRAN 3) Logo
2) Basic 4) Fractal
17. The Image(filename) method of the Image class raises an error if the filename is not
found or the file is not a(n) ____ file.
1) RGB 3) JPEG
2) GIF 4) Python
18. A(n) ____ graphics toolkit provides a simple and enjoyable way to draw pictures in a window
and gives you an opportunity to run several methods with an object.
1) Vector 3) RGB
2) Turtle 4) Fractal
19. Resolution is measured in pixels or ____.
1) DPI 3) JPEG
2) GIF 4) PY
20. Two of the most popular image file formats are JPEG and ____.
1) XML 3) PDF
2) PY 4) GIF
21. The RGB value of the red color is ____.
1) (0, 0, 0) 3) (255, 0, 0)
2) (0, 0, 255) 4) (255, 255, 255)
36
22. The method ____ of the Image class builds and returns a new image with the same attributes
as the original one, but with an empty string as the filename.
1) clone 3) duplicate
2) copy 4) instantiate
23. Python’s ____ mechanism allows the programmer to view an interface for an entire class or an
individual method, at the shell prompt.
1) API 3) docstring
2) help 4) man
24. Computers must use digital information consisting of ____ values, such as individual integers,
characters of text, or bits in a bit string.
1) discrete 3) analog
2) continuous 4) Euclidean
25. Among the various schemes for representing colors, the ____ system is a fairly common one.
1) RGB 3) vector
2) bitmap 4) fractal
END OF EXAM
37
Chapter 8 - Design with Classes
LESSON 9306C
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Lesson Assignment
Chapter Notes
Overview
Chapter 8 provides an introduction to objects and classes with Python. You learn about
object-oriented design and how to create object-oriented programs in Python. Important
OO concepts like constructors, instance variables, methods, inheritance, polymorphism,
and encapsulation are introduced. Special topics like exception handling (try-
exception) and how to transfer objects to and from files (pickling/unpickling) are
introduced as well.
Objectives
After completing this chapter, you will be able to:
Determine the attributes and behavior of a class of objects required by a program
List the methods, including their parameters and return types, that realize the behavior
of a class of objects
Choose the appropriate data structures to represent the attributes of a class of objects
Define a constructor, instance variables, and methods for a class of objects
38
Recognize the need for a class variable and define it
Define a method that returns the string representation of an object
Define methods for object equality and comparisons
Exploit inheritance and polymorphism when developing classes
Transfer objects to and from files
Topic Tips
Getting Inside Objects and Classes
Topic Tip
Note for C/C++/Java/C# Programmers (taken from
www.ibiblio.org/g2swap/byteofpython/read/oops.html): “Note that even
integers are treated as objects (of the int class). This is unlike C++ and Java
(before version 1.5) where integers are primitive native types. See help(int) for
more details on the class. C# and Java 1.5 programmers will be familiar with this
concept since it is similar to the boxing and unboxing concept.”
Topic Tip For an introduction to object-oriented programming with Python, read:
www.voidspace.org.uk/python/articles/OOP.shtml.
Topic Tip For more information on how to define classes in Python, read:
http://diveintopython.org/object_oriented_framework/defining_classes.html.
Topic Tip
“Is self a Wart ? Some people regard it as a Python ‘wart’ that we have to
include self. Java includes it automatically and calls it this. The main
argument in favor of self is the Pythonic principle explicit is better than
implicit. This way we can see exactly where all our variable names come from.”
Reference: www.voidspace.org.uk/python/articles/OOP.shtml.
Quick Quiz 1
1. Why is an object considered an abstraction?
2. True or False: In a class, all of the method definitions are indented below the class
header.
3. True or False: Within the class definition, the names of instance variables must begin
with this.
4. Methods that allow a user to modify an object’s state are called
____________________.
39
Data-Modeling Examples
Topic Tip
For more information on operator overloading in Python, read:
www.learningpython.com/2008/06/21/operator-overload-learn-how-to-
change-the-behavior-of-equality-operators/.
Topic Tip For more information on errors and exceptions in Python, read:
http://docs.python.org/tut/node10.html.
Quick Quiz 2
1. True or False: The code x + y is actually shorthand for the code y.__add__(x).
2. To overload the % arithmetic operator, you need to define a new method using
____________________ as the method name.
3. What is operator overloading?
4. What is a class variable?
Structuring Classes with Inheritance and Polymorphism
Topic Tip
“Python does not really support encapsulation because it does not support data
hiding through private and protected members. However some pseudo-
encapsulation can be done. If an identifier begins with a double underline, i.e.
__a, then it can be referred to within the class itself as self.__a, but outside
of the class, it is named instance._classname__a. Therefore, while it can
prevent accidents, this pseudo-encapsulation cannot really protect data from
hostile code.”
Reference: www.astro.ufl.edu/~warner/prog/python.html.
Topic Tip
For an interesting discussion on why Python does not support data hiding
(encapsulation), read: http://mail.python.org/pipermail/python-list/2008-
June/494162.html.
40
Topic Tip
“Abstract classes and interfaces are not supported in Python. In Python, there is
no difference between an abstract class and a concrete class. Abstract classes
create a template for other classes to extend and use. Instances cannot be created
of abstract classes but they are very useful when working with several objects
that share many characteristics. For instance, when creating a database of people,
one could define the abstract class Person, which would contain basic
attributes and functions common to all people in the database. Then child classes
such as SinglePerson, MarriedCouple, or Athlete could be created by
extending Person and adding appropriate variables and functions. The database
could then be told to expect every entry to be an object of type Person and thus
any of the child classes would be a valid entry. In Python, you could create a
class Person and extend it with the child classes listed above, but you could not
prevent someone from instantiating the Person class.”
Reference: www.astro.ufl.edu/~warner/prog/python.html.
Quick Quiz 3
1. ____________________ restricts the manipulation of an object’s state by external users
to a set of method calls.
2. ____________________ allows a class to automatically reuse and extend the code of
similar but more general classes.
3. What is polymorphism?
4. True or False: In Python, all classes automatically extend the built-in object class.
Additional Resources
1. Python Basics:
www.astro.ufl.edu/~warner/prog/python.html
2. Introduction to OOP with Python:
www.voidspace.org.uk/python/articles/OOP.shtml
3. Defining Classes:
http://diveintopython.org/object_oriented_framework/defining_classes.html
4. An Introduction to Python: Classes:
www.penzilla.net/tutorials/python/classes/
5. Classes:
http://docs.python.org/tut/node11.html
6. Errors and Exceptions:
41
http://docs.python.org/tut/node10.html
Key Terms
abstract class: A class that defines attributes and methods for subclasses, but is never
instantiated.
accessor: A method used to examine an attribute of an object without changing it.
analysis: The phase of the software life cycle in which the programmer describes what
the program will do.
arithmetic overflow: A situation that arises when the computer’s memory cannot
represent the number resulting from an arithmetic operation.
behavior: The set of actions that a class of objects supports.
class: A description of the attributes and behavior of a set of computational objects.
class diagram: A graphical notation that describes the relationships among the classes
in a software system.
class variable: A variable that is visible to all instances of a class and is accessed by
specifying the class name.
concrete class: A class that can be instantiated.
constructor: A method that is run when an object is instantiated, usually to initialize
that object’s instance variables. This method is named _init_ in Python.
debugging: The process of eliminating errors, or bugs, from a program.
encapsulation: The process of hiding and restricting access to the implementation
details of a data structure.
float: A Python data type used to represent numbers with a decimal point, for example,
a real number or a floating-point number.
garbage collection: The automatic process of reclaiming memory when the data of a
program no longer need it.
helper: A method or function used within the implementation of a module or class but
not used by clients of that module or class.
identifiers: Words that must be created according to a well-defined set of rules but can
have any meaning subject to these rules.
if-else statement: A selection statement that allows a program to perform alternative
actions based on a condition.
implementation: The phase of the software life cycle in which the program is coded in
a programming language.
inheritance: The process by which a subclass can reuse attributes and behavior defined
in a superclass. See also subclass and superclass.
instance variable: Storage for data in an instance of a class.
method header: The portion of a method implementation containing the method’s
name and parameter names.
model/view/controller pattern (MVC): A design plan in which the roles and
responsibilities of the system are cleanly divided among data management (model), user
interface display (view), and user event-handling (controller) tasks.
mutator: A method used to change the value of an attribute of an object.
object-oriented programming: The construction of software systems that define
classes and rely on inheritance and polymorphism.
42
overloading: The process of using the same operator symbol or identifier to refer to
many different functions.
parent: A given node’s predecessor in a tree. Also, the immediate superclass of a class.
polymorphism: The property of one operator symbol or method identifier having many
meanings. See also overloading.
procedural programming: A style of programming that decomposes a program into a
set of methods or procedures.
random access data structure: A data structure in which the time to access a data item
does not depend on its position in the structure.
software reuse: The process of building and maintaining software systems out of
existing software components.
subclass: A class that inherits attributes and behaviors from another class.
superclass: The class from which a subclass inherits attributes and behavior.
Unified Modeling Language (UML): A graphical notation for describing a software
system in various phases of development.
43
Python Lesson 9306C Exam
Please complete the following exam. You may use the electronic grading system for quicker
response. Simply log on to www.study-electronics.com and enter your credentials. Once the
exam has been submitted, your results will be returned within 72 hours. You may also e-mail
your answers to [email protected], or fax them to us at 1-216-781-0331. If you have any
questions, please contact the Instruction Department.
Multiple Choice
Identify the choice that best completes the statement or answers the question.
1. Methods that allow a user to observe but not change the state of an object are called ____.
1) observers 3) readers
2) accessors 4) input methods
2. A(n) ____ class includes data and methods common to its subclasses, but is never instantiated.
1) polymorphic 3) encapsulated
2) abstract 4) anonymous
3. The ____ definition syntax has two parts: a header and a set of method definitions that follow
the header.
1) object 3) function
2) class 4) module
4. The use of cooperating subprograms to solve problems is called ____ programming.
1) imperative 3) procedural
2) object-oriented 4) functional
5. ____ returns -1.
1) cmp(1, 1) 3) cmp(2, 1)
2) cmp(1, 2) 4) cmp(1, -1)
6. A(n) ____ number consists of two integer parts, a numerator and a denominator.
1) real 3) rational
2) abstract 4) imaginary
7. Python includes a module that allows the programmer to save and load objects using a process
called ____.
1) serializing 3) pickling
2) streaming 4) converting
8. The ____ operator returns True if self and other refer to the exact same object.
1) is 3) in
2) equals 4) eq
9. Most classes include a special method named ____, which is the class’s constructor.
1) _self 3) _init
2) __self__ 4) __init__
44
10. Methods that allow a user to modify an object’s state are called ____.
1) mutators 3) writers
2) modifiers 4) output methods
11. Pickled objects can be loaded into a program from a file using the function ____.
1) cPickle.load 3) cPickle.input
2) cPickle.read 4) cPickle.pickleIn
12. In a class diagram, the name of each class appears in a ____.
1) callout 3) circle
2) triangle 4) box
13. To pickle an object, you start by importing the ____ module.
1) pickle 3) pPickle
2) pickles 4) cPickle
14. ____ is used to describe and document the analysis and design of complex software systems.
1) HTML 3) XML
2) SVG 4) UML
15. In Python, all classes automatically extend the built-in ____ class, which is the most general
class possible.
1) class 3) object
2) base 4) self
16. The ____ method builds and returns a string representation of an object’s state.
1) self 3) str
2) __self__ 4) __str__
17. In general, it is a good idea to divide the code for most interactive applications into at least
____ sets of classes.
1) two 3) four
2) three 4) five
18. The code x + y is actually shorthand for the code ____.
1) x.add(y) 3) (x)__add__(y)
2) x._add(y) 4) x.__add__(y)
19. ____ restricts the manipulation of an object’s state by external users to a set of method calls.
1) Data encapsulation 3) Polymorphism
2) Inheritance 4) Abstraction
20. Python allows the programmer to ____ many of the built-in operators for use with new data
types.
1) overload 3) recreate
2) redefine 4) define
21. Python’s ____ statement allows an exception to be caught and the program to recover.
1) try-catch 3) assert
2) try-except 4) except
45
22. Code in the ____ programming style consists of input and output statements, assignment
statements, and control statements for selection and iteration.
1) imperative 3) procedural
2) object-oriented 4) functional
23. Python’s ____ function is used to determine whether or not two objects are of the same type.
1) is 3) in
2) type 4) eq
24. Each method definition must include a first parameter named ____, even if that method seems
to expect no arguments when called.
1) self 3) object
2) class 4) this
25. The ____ method of the float or int class returns 0 if the operands are equal, -1 if the left
operand is less than the right one, or 1 if the left operand is greater than the right one.
1) cmp 3) compare
2) __cmp__ 4) __compare__
END OF EXAM
46
Chapter 9 - Graphical User Interfaces
LESSON 9307C
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Lesson Assignment
Chapter Notes
Overview
Chapter 9 provides an introduction to graphical user interfaces. You learn about the
structure of a GUI-based program and using the MVC pattern. Through several
examples, you learn to instantiate and lay out different types of window objects, such as
labels, entry fields, and command buttons, in a window’s frame. Events and event-
driven programming are also introduced, and you learn to define methods that handle
events associated with window objects. Achieving different layouts using grids and
nested frames (panes) is also covered.
Objectives
After completing this chapter, you will be able to:
Structure a GUI-based program using the model/view/controller pattern
Instantiate and lay out different types of window objects, such as labels, entry fields,
and command buttons, in a window’s frame
Define methods that handle events associated with window objects
Organize sets of window objects in nested frames
47
Topic Tips
The Behavior of Terminal-Based Programs and GUI-Based Programs
Topic Tip
The PyjamasDesktop Python toolkit uses the PyWebkitGtk toolkit and provides
the "V" in the MVC pattern. For more information, visit:
http://wiki.python.org/moin/PyjamasDesktop.
Quick Quiz 1
1. What is a GUI?
2. GUI-based programs display windows that contain various components, also called
window objects or ____________________.
3. True or False: In a GUI-based program, a status bar contains the title of the program.
4. What are entry fields?
Coding Simple GUI-Based Programs
Topic Tip
Python has a huge number of GUI frameworks (or toolkits) available for it. You
can find a list of several of these toolkits at:
http://wiki.python.org/moin/GuiProgramming.
Topic Tip
Tkinter is based on the Tk widget set (a package to implement GUI programs
under a windowing system). For more information on Tkinter, visit:
http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html.
Topic Tip For more information on the tkMessageBox module, visit:
http://epydoc.sourceforge.net/stdlib/tkMessageBox-module.html.
Quick Quiz 2
1. What is Tkinter?
2. ____________________ is a Python standard module that includes classes for windows
and numerous types of window objects.
48
3. True or False: In programs that use several buttons, each button has its own event-
handling method.
4. A form filler consists of labeled ____________________ fields, which allow the user to
enter and edit a single line of text.
Other Useful GUI Resources
Topic Tip For more information on the Tkinter grid geometry manager, visit:
http://effbot.org/tkinterbook/grid.htm.
Topic Tip
“TK provides three geometry managers: .pack(), .grid() and
.place().” For more information, visit:
www.ibm.com/developerworks/linux/library/l-tkprg/.
Topic Tip
For more information on events and bindings in Python, read:
www.pythonware.com/library/tkinter/introduction/events-and-
bindings.htm.
Quick Quiz 3
1. True or False: In Python, a hex literal begins with the % symbol.
2. How can the user resize a window?
3. True or False: By default, a newly opened window shrink-wraps around its components
and is resizable.
4. A nested frame is sometimes called a(n) ____________________.
Additional Resources
1. GUI Programming in Python:
http://wiki.python.org/moin/GuiProgramming
2. Tkinter: GUI programming with Python:
http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html
3. Graphic User Interface FAQ:
www.python.org/doc/faq/gui/
4. Module tkMessageBox:
http://epydoc.sourceforge.net/stdlib/tkMessageBox-module.html
49
5. The Tkinter Grid Geometry Manager:
http://effbot.org/tkinterbook/grid.htm
6. Events and Bindings:
www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
Key Terms
attribute: A property that a computational object models, such as the balance in a bank
account.
button object: A window object that allows the user to select an action by clicking a
mouse.
event: An occurrence, such as a button click or a mouse motion, that can be detected
and processed by a program.
event-driven loop: A process, usually hidden in the operating system, that waits for an
event, notifies a program that an event has occurred, and returns to wait for more
events.
grid layout: A Python layout class that allows the user to place window objects in a
two-dimensional grid in the window.
GUI (graphical user interface): A means of communication between human beings
and computers that uses a pointing device for input and a bitmapped screen for output.
The bitmap displays images of windows and window objects such as buttons, text
fields, and drop-down menus. The user interacts with the interface by using the mouse
to directly manipulate the window objects. See also window object.
helper: A method or function used within the implementation of a module or class but
not used by clients of that module or class.
justification: The process of aligning text to the left, the center, or the right within a
given number of columns.
label object: A window object that displays text, usually to describe the roles of other
window objects.
model/view/controller pattern (MVC): A design plan in which the roles and
responsibilities of the system are cleanly divided among data management (model), user
interface display (view), and user event-handling (controller) tasks.
terminal I/O interface: A user interface that allows the user to enter input from a
keyboard and view output as text in a window. Also called a terminal-based interface.
window object (widget): A computational object that displays an image, such as a
button or a text field, in a window and supports interaction with the user.
50
Python Lesson 9307C Exam
Please complete the following exam. You may use the electronic grading system for quicker
response. Simply log on to www.study-electronics.com and enter your credentials. Once the
exam has been submitted, your results will be returned within 72 hours. You may also e-mail
your answers to [email protected], or fax them to us at 1-216-781-0331. If you have any
questions, please contact the Instruction Department.
Multiple Choice
Identify the choice that best completes the statement or answers the question.
1. In GUI-based programs, mouse-clicks are user-generated ____.
1) triggers 3) labels
2) events 4) commands
2. In GUI terminology, a nested frame is sometimes called a ____.
1) grid 3) pane
2) widget 4) tab
3. A(n) ____ layout allows the programmer to place components in the cells of an invisible grid in
the window.
1) cell 3) MVC
2) grid 4) model/view
4. The default value for the column Grid attribute is ____.
1) 0 3) "left"
2) False 4) "right"
5. The ____ color of a label or an entry field is its text color.
1) line 3) foreground
2) pen 4) background
6. In GUI-based applications, groups of GUI-components can be nested in multiple ____ in a
window.
1) tabs 3) grids
2) panes 4) frames
7. A ____ exception is raised when Python attempts to convert a string with a bad format to a
number.
1) ConversionError 3) ParsingError
2) ValueError 4) FormatError
8. The ____ tkMessageBox function shows a warning message.
1) showerror 3) showwarning
2) showinfo 4) showmessage
9. A form ____ consists of labeled entry fields, which allow the user to enter and edit a single line
of text.
1) filler 3) widget
2) set 4) grid
51
10. The ____ mouse event occurs when the mouse cursor has left the widget.
1) <Off-Focus> 3) <Out-of-Focus>
2) <Leave> 4) <Abandon>
11. In GUI-based programs, ____ are text elements that describe the inputs and outputs.
1) labels 3) command buttons
2) title bars 4) entry fields
12. The ____ keyboard event occurs when any key has been pressed.
1) <KeyPress> 3) <On-Key-Press>
2) <KeyPressed> 4) <Key-Pressed>
13. GUI-based programs rely extensively on pop-up ____ that display messages, query the user for
a Yes/No answer, and so forth.
1) widgets 3) windows
2) grids 4) dialog boxes
14. Python includes a ____ widget for the display of multiple lines of text.
1) MultiLine 3) MultiText
2) TextBox 4) Text
15. In the RGB system, the value ____ represents the color black.
1) #000000 3) #bbbbbb
2) #999999 4) #ffffff
16. To activate a button and enable it to respond to mouse clicks, you must set its command
attribute to a(n) ____ method.
1) label 3) trigger
2) widget 4) event-handling
17. The ____ Grid attribute specifies how to distribute extra space in the widget’s cell.
1) rowspan 3) padding
2) sticky 4) pady
18. GUI-based programs adhere to the ____ pattern.
1) observer 3) model/view
2) controller 4) event
19. Access to the items in a list box is index-based. The index of any item in a list box may be
specified with ____.
1) a zero-based integer 3) user-defined constants
2) a one-based integer 4) a string
20. In GUI-based programs, ____ are boxes within which the program can output text or receive it
as input from the user.
1) labels 3) command buttons
2) title bars 4) entry fields
21. A user’s editing within a Text widget can be disabled by setting its state attribute to ____.
1) NONE 3) BLOCKED
2) False 4) DISABLED
52
22. In the ____ color system, a color consists of three integer components that specify the
intensities of red, green, and blue mixed into that color.
1) RGB 3) GIF
2) CMYK 4) JPEG
23. In the RGB system, the value ____ represents the color white.
1) #000000 3) #wwwwww
2) #999999 4) #ffffff
24. The ____ class includes a wide array of methods for managing items in a list box.
1) Tkinter.ListBox 3) Tkinter.TextBox
2) Tkinter.Listbox 4) Tkinter.Textbox
25. You can associate a mouse event and an event-handling method with a widget by calling the
____ method.
1) assign 3) bind
2) associate 4) link
END OF EXAM
53
Chapter 11 - Searching, Sorting, and Complexity Analysis
LESSON 9308C
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Chapter Notes
Overview
Chapter 11 describes searching, sorting, and complexity analysis. You begin by learning
the different ways in which one can measure the performance of an algorithm. Big-O
notation is introduced next; emphasis is given to how to distinguish the common orders
of complexity, and the algorithmic patterns that exhibit them. Finally, you study several
search and sort algorithms and analyze their complexity.
Objectives
After completing this chapter, you will be able to:
Measure the performance of an algorithm by obtaining running times and instruction
counts with different data sets
Analyze an algorithm’s performance by determining its order of complexity, using big-
O notation
Distinguish the common orders of complexity and the algorithmic patterns that exhibit
them
Distinguish between the improvements obtained by tweaking an algorithm and reducing
its order of complexity
Write a simple linear search algorithm and a simple sort algorithm
54
Topic Tips
Measuring the Efficiency of Algorithms
Topic Tip For more information on the subject of Analysis of Algorithms, read:
http://en.wikipedia.org/wiki/Analysis_of_algorithms.
Complexity Analysis
Topic Tip For more information on big-O notation, visit:
www.nist.gov/dads/HTML/bigOnotation.html.
Quick Quiz 1
1. What is benchmarking?
2. True or False: Complexity analysis entails reading an algorithm and using pencil and
paper to work out some simple algebra.
3. True or False: An algorithm has linear performance if it requires the same number of
operations for any problem size.
4. The constant of ____________________ involves the terms and coefficients that are
usually ignored during big-O analysis.
Search Algorithms
Topic Tip For more information on search algorithms, read:
http://en.wikipedia.org/wiki/Search_algorithm.
Quick Quiz 2
1. Python’s ____________________ function returns the minimum or smallest item in a
list.
2. True or False: Python’s is operator is implemented as a method named
__contains__ in the list class.
55
3. True or False: The worst-case complexity of a linear search is O(n).
4. When searching sorted data, it is better to use a(n) ____________________ search than
a sequential search.
Sort Algorithms
Topic Tip For more information on sorting algorithms, visit:
http://en.wikipedia.org/wiki/Sorting_algorithm.
Topic Tip
You can find online selection sort demos at:
http://web.engr.oregonstate.edu/~minoura/cs162/javaProgs/sort/SelectSort.html
http://vision.bc.edu/~dmartin/Topic/sorting/anim-html/selection.html
Topic Tip
You can find online bubble sort demos at:
www.ndsu.nodak.edu/instruct/juell/vp/cs1and2/sortdemo/BubbleSortDemo_ny.
html
http://web.engr.oregonstate.edu/~minoura/cs261/javaProgs/sort/BubbleSort.html
http://vision.bc.edu/~dmartin/Topic/sorting/anim-html/bubble.html
http://coderaptors.com/?BubbleSort
Topic Tip
You can find online insertion sort demos at:
http://web.engr.oregonstate.edu/~minoura/cs162/javaProgs/sort/InsertSort.html
http://vision.bc.edu/~dmartin/Topic/sorting/anim-html/insertion.html
Topic Tip
For more information on useful sorting demonstrations, visit:
www.bluffton.edu/~nesterd/java/SortingDemo.html
www.cs.rit.edu/~atk/Java/Sorting/sorting.html
www.cs.oswego.edu/~mohammad/classes/csc241/samples/sort/Sort2-E.html
Quick Quiz 3
1. How does selection sort work?
2. True or False: The performance of bubble sort is O(n).
3. The worst-case behavior of insertion sort is O(____________________).
4. True or False: Exponential algorithms are generally impractical to run with any but very
small problem sizes.
56
Case Study: An Algorithm Profiler
Topic Tip For more information on the use of profilers, visit:
http://en.wikipedia.org/wiki/Performance_analysis#Use_of_profilers.
Additional Resources
1. Analysis of algorithms:
http://en.wikipedia.org/wiki/Analysis_of_algorithms
2. Big-O notation:
www.nist.gov/dads/HTML/bigOnotation.html
3. Search algorithm:
http://en.wikipedia.org/wiki/Search_algorithm
4. Sorting algorithm:
http://en.wikipedia.org/wiki/Sorting_algorithm
5. Sorting demonstrations:
www.bluffton.edu/~nesterd/java/SortingDemo.html
6. Sorting algorithms:
www.cs.rit.edu/~atk/Java/Sorting/sorting.html
7. Dictionary of algorithms and data structures:
www.nist.gov/dads/
Key Terms
algorithm(s): A finite sequence of instructions that, when applied to a problem, will
solve it.
asymptotic analysis: The process of approximating the performance of an algorithm by
focusing on the largest degree term of a polynomial.
behavior: The set of actions that a class of objects supports.
benchmarking: The process of measuring the performance of an algorithm by timing it
on a real computer.
big-O notation: A formal notation used to express the amount of work done by an
algorithm or the amount of memory used by an algorithm.
binary search: The process of examining a middle value of a sorted collection to see
which half contains the value in question and halving until the value is located.
bubble sort: A sorting algorithm that swaps consecutive elements that are out of order
to bubble the elements to the top or bottom on each pass.
57
complexity analysis: The process of deriving a formula that expresses the rate of
growth of work or memory as a function of the size of the data or problem that it solves.
See also big-O notation.
constant of proportionality: The measure of the amount of work of an algorithm that
never varies with the size of its data set.
counter: A variable used to count the number of times some process is completed.
Fibonacci numbers: A series of numbers generated by taking the sum of the previous
two numbers in the series. The series begins with the numbers 0 and 1.
helper: A method or function used within the implementation of a module or class but
not used by clients of that module or class.
insertion sort: A sorting algorithm that locates an insertion point and takes advantage
of partial orderings in an array.
linear: An increase of work or memory in direct proportion to the size of a problem.
logarithmic: An increase of work in proportion to the number of times that the problem
size can be divided by 2.
quadratic: An increase of work or memory in proportion to the square of the size of the
problem.
recursive function: A function that calls itself.
selection sort: A sorting algorithm that sorts the components of a list in either
ascending or descending order. This process puts the smallest or largest element in the
top position and repeats the process on the remaining list components.
sequential search: The process of searching a list by examining the first component
and then examining successive components in the order in which they occur. Also
referred to as a linear search.
Continue to the next chapter for the lesson exam
58
Chapter 13 - Collections, Arrays, and Linked Structures
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Lesson Assignment
Chapter Notes
Overview
Chapter 13 describes collections, arrays, and linked structures. You learn how to
recognize the different categories of collections. The concepts of abstract data type and
data structure are introduced. Next, the chapter covers how to perform and implement
basic operations on arrays and linked structures. For each operation, examples and a
space/time trade-off analysis are provided.
Objectives
After completing this chapter, you will be able to:
Recognize different categories of collections and the operations on them
Understand the difference between an abstract data type and the concrete data structures
used to implement it
Perform basic operations on arrays, such as insertions and removals of items
Resize an array when it becomes too small or too large
Describe the space/time trade-offs for users of arrays
59
Perform basic operations, such as traversals, insertions, and removals, on linked
structures
Explain the space/time trade-offs of arrays and linked structures in terms of the memory
models that underlie these data structures
Topic Tips
Overview of Collections
Topic Tip
“In computer science, a graph is a kind of data structure, specifically an abstract
data type (ADT) that consists of a set of nodes (also called vertices) and a set of
edges that establish relationships (connections) between the nodes. The graph
ADT follows directly from the graph concept from mathematics.”
Reference: http://en.wikipedia.org/wiki/Graph_data_structure.
Data Structures for Implementing Collections: Arrays
Topic Tip For more information on arrays, read: http://en.wikipedia.org/wiki/Array and
http://en.wikibooks.org/wiki/Data_Structures/Arrays.
Quick Quiz 1
1. What is a hierarchical collection?
2. True or False: Collections are typically static rather than dynamic.
3. A collection is an abstraction, and for this reason, in computer science, collections are
called ____________________ (ADTs).
4. True or False: Array indexing is a random access operation.
Operations on Arrays
Topic Tip For a comparison on how different programming languages implement arrays, see:
http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(array).
Two-Dimensional Arrays (Grids)
60
Topic Tip You can find a graphical representation of a multidimensional array at:
http://en.wikibooks.org/wiki/Data_Structures/Arrays.
Quick Quiz 2
1. True or False: Removing an item from an array involves the inverse process of inserting
an item into the array.
2. What is an array’s load factor?
3. True or False: Two-dimensional arrays are also called vectors.
4. A(n) ____________________ array can be visualized as a box filled with smaller boxes
stacked neatly in rows and columns.
Linked Structures
Topic Tip For more information on linked lists, read:
http://en.wikipedia.org/wiki/Linked_list.
Operations on Singly Linked Structures
Topic Tip
You can find a useful Java Applet that can be used to help illustrate insertion and
removal on singly linked structures at:
www.cosc.canterbury.ac.nz/mukundan/dsal/LinkListAppl.html.
Topic Tip Radix sort is a sorting algorithm that can be particularly effective on a linked list.
Reference: http://nist.gov/dads/HTML/radixsort.html.
Variations on a Link
Topic Tip For more information on circular linked structures and doubly linked structures,
read: http://en.wikipedia.org/wiki/Linked_list.
Topic Tip You can find many linked list problems for your students to practice at:
http://cslibrary.stanford.edu/105/.
61
Quick Quiz 3
1. A user of a singly linked structure accesses the first item by following a single external
____________________ link.
2. True or False: The basic unit of representation in a linked structure is an object.
3. True or False: In singly linked structures, traversals are linear in time and require no
extra memory.
4. What is a circular linked structure?
Additional Resources
1. Data types:
www.python.org/doc/2.5.2/lib/datatypes.html
2. Array:
http://en.wikipedia.org/wiki/Array
3. Arrays:
http://en.wikibooks.org/wiki/Data_Structures/Arrays
4. Linked list:
http://en.wikipedia.org/wiki/Linked_list
Key Terms
abstraction: A simplified view of a task or data structure that ignores complex detail.
address: An integer value that the computer can use to reference a memory cell.
ADTs (abstract data types): A class of objects, a defined set of properties of those
objects, and a set of operations for processing the objects.
array(s): A data structure whose elements are accessed by means of index positions.
base address: The memory address of the first cell in an array.
children: Elements that are directly below a given element in a hierarchical collection.
circular linked structure: A linked structure in which the next pointer of the last node
is aimed at the first node.
collection: A group of data elements that can be treated as one thing. A collection
tracks several elements, which can be added or removed.
concrete data type: A data structure that is used to contain the data in an
implementation of an abstract data type. See also data structure.
contiguous memory: Computer memory that is organized so that the data are
accessible in adjacent cells.
data structure: A compound unit consisting of several data values.
decrement: To decrease the value of a variable.
62
deep copy: The process whereby copies are made of the individual components of a
data structure.
doubly linked node: A node that has a pointer to the previous node and a pointer to the
next node.
doubly linked structure: A linked structure in which each node has a pointer to the
previous node and a pointer to the next node.
dummy header node: A special node that does not contain data, but lies at the
beginning of a linked structure and makes insertions and removals simpler.
dynamic: Pertaining to the run-time behavior of a program or allocation of memory.
dynamic array: An array whose storage requirements can be determined at run time.
empty link: A value used to indicate the absence of a link to another node.
garbage: Data that are no longer accessible to a program or no longer have a meaning
within it.
graph collection (graph): A collection whose elements may have zero or more
predecessors and successors.
grid: A data structure in which the items are accessed by specifying at least two index
positions, one that refers to the item’s row and another that refers to the item’s column.
head link: An external link that is either empty or points to the first node in a linked
structure.
hierarchical collection: A collection whose elements may have zero or more
successors, but at most one predecessor.
iterable: The property of a collection that allows a programmer to traverse it with a
simple for loop. See also iterator.
linear collection: A collection whose elements have at most one predecessor and at
most one successor.
linked structure: A structure in which each item is linked to the next one by means of
a pointer. See also recursive data structure.
load factor: A measure of the degree to which an array is filling with items, computed
by dividing the number of items by the array’s capacity.
logical size: The number of data items actually available in a data structure at a given
time. See also physical size.
matrix: A two-dimensional array that provides range checking and can be resized.
multidimensional array: An array whose elements are accessed by specifying more
than one index.
neighbors: Two vertices connected by an edge.
noncontiguous memory: A type of memory that allows adjacent items in a data
structure to be stored in memory cells that are not adjacent in the computer.
object heap: An area of computer memory from which storage for objects is allocated.
offset: The quantity added to the base address of an array to locate the address of an
array cell.
one-dimensional array: An array in which each data item is accessed by specifying a
single index.
parent: A given node’s predecessor in a tree. Also, the immediate superclass of a class.
physical size: The number of memory units available for storing data items in a data
structure.
pointer: A reference to an object that allows you to access it.
random access: A data-access method that runs in constant time.
reference: The process of accessing or looking up the value of a variable or,
alternatively, a pointer to an object.
63
sentinel value (sentinel): A special value that indicates the end of a set of data or of a
process.
singly linked node: A node that contains a single pointer, which is either empty or
refers to the next node.
static: Pertaining to data whose memory requirements are fixed and cannot be changed.
stopping state: The well-defined termination of a recursive process.
traversal: The process of iterating through the items of a collection so that each item is
visited once.
two-dimensional array: An array in which each data item is accessed by specifying a
pair of indices.
unordered collection: A collection whose elements are in no particular order from the
client’s perspective.
64
Python Lesson 9308C Exam
Please complete the following exam. You may use the electronic grading system for quicker
response. Simply log on to www.study-electronics.com and enter your credentials. Once the
exam has been submitted, your results will be returned within 72 hours. You may also e-mail
your answers to [email protected], or fax them to us at 1-216-781-0331. If you have any
questions, please contact the Instruction Department.
Multiple Choice
Identify the choice that best completes the statement or answers the question.
1. In a singly linked structure, traversals are ____ in time.
1) constant 3) quadratic
2) linear 4) exponential
2. If the ____, there is no more room for data in the array.
1) logical size of an array equals the physical size
2) logical size of an array is greater than the physical size
3) physical size of an array is 0
4) logical size of an array is 0
3. Bubble sort is ____.
1) O(n2) 3) O(n)
2) O(log2n) 4) O(1)
4. The work of a(n) ____ time algorithm grows at a rate of nk, where k is a constant greater than 1.
1) exponential 3) logarithmic
2) polynomial 4) constant
5. ____ complexity is the best kind of performance to have.
1) Quadratic 3) Logarithmic
2) Linear 4) Constant
6. If the ____, the array is empty.
1) logical size of an array equals the physical size
2) logical size of an array is greater than the physical size
3) physical size of an array is 0
4) logical size of an array is 0
7. A ____ linked structure contains a link from the last node back to the first node in the structure.
1) complete 3) singly
2) doubly 4) circular
8. The performance of an algorithm is ____ if its work grows in direct proportion to the size of the
problem.
1) quadratic 3) logarithmic
2) linear 4) constant
65
9. Items in a(n) ____ collection are not in any particular order, and one cannot meaningfully speak
of an item’s predecessor or successor.
1) linear 3) unordered
2) graph 4) hierarchical
10. In a(n) ____ copy of a collection both the structure and the items are copied.
1) cloning 3) shallow
2) deep 4) exact
11. Array indexing is a(n) ____ access operation.
1) linear 3) random
2) abstract 4) static
12. The best-case complexity of a linear search is ____.
1) O(n2) 3) O(n)
2) O(log2n) 4) O(1)
13. In computer science, collections are called ____.
1) UMLs 3) data structures
2) graphs 4) ADTs
14. In a singly linked structure, removing data at the beginning is ____ in time.
1) constant 3) quadratic
2) linear 4) exponential
15. The ____ size of an array is its total number of array cells, or the number used to specify its
capacity when the array is created.
1) physical 3) static
2) logical 4) dynamic
16. The time() function returns the number of seconds that have elapsed between the current
time on the computer’s clock and January 1, ____ (also called “The Epoch”).
1) 1950 3) 1970
2) 1960 4) 1980
17. In an array, the time performance for the removal operation is ____.
1) constant 3) quadratic
2) linear 4) exponential
18. ____ analysis entails reading the algorithm and using pencil and paper to work out some simple
algebra.
1) Complexity 3) Memory
2) Algorithm 4) Efficiency
19. One notation that computer scientists use to express the efficiency or computational complexity
of an algorithm is called big-____ notation.
1) O 3) C
2) P 4) G
20. The average complexity of a linear search is ____.
1) O(n2) 3) O(n)
2) O(log2n) 4) O(1)
66
21. Python programmers set up nodes and linked structures by using ____ to objects.
1) references 3) memory addresses
2) pointers 4) links
22. Two-dimensional arrays are also called ____.
1) lists 3) grids
2) vectors 4) clusters
23. The difference between the results of two calls of ____ represents the elapsed time in seconds.
1) time.time() 3) time.ctime()
2) ctime.time() 4) ctime.ctime()
24. In the worst case of a linear search, the target item is ____.
1) at the beginning of the list
2) at the beginning of the list or not in the list at all
3) at the end of the list
4) at the end of the list or not in the list at all
25. In a(n) ____ grid, there are a fixed number of rows, but the number of columns of data in each
row can vary.
1) irregular 3) unbalanced
2) dynamic 4) ragged
26. The performance of an algorithm is ____ if its amount of work is proportional to the log2 of
the problem size.
1) quadratic 3) logarithmic
2) linear 4) constant
END OF EXAM
67
Chapter 14 - Linear Collections: Stacks
LESSON 9309C
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Lesson Assignment
Chapter Notes
Overview
Chapter 14 introduces stacks as linear collections. You learn about the behavior of a
stack from a user’s perspective, and learn how to use stacks in three different settings: a
backtracking algorithm, to evaluate postfix expressions, and in a virtual machine to
support function and method calls. Finally, you analyze the performance trade-offs
between an array-based implementation of a stack and a linked implementation of a
stack.
Objectives
After completing this chapter, you will be able to:
Describe the behavior of a stack from a user’s perspective
Explain how a stack can be used to support a backtracking algorithm
Describe the use of a stack in evaluating postfix expressions
Explain how the Python virtual machine uses a stack to support function and method
calls
68
Analyze the performance trade-offs between an array-based implementation of a stack
and a linked implementation of a stack
Topic Tips
Overview of Stacks
Topic Tip
For more detailed information on stacks, read:
http://en.wikipedia.org/wiki/Stack_(data_structure) and
www.nist.gov/dads/HTML/stack.html.
Topic Tip For a useful interactive applet to help show your students how a stack works,
visit: www.cmpe.boun.edu.tr/~akin/cmpe223/stack_queue/chap2_2.htm.
Topic Tip For a comprehensive list of stack animations and visualizations, visit:
http://algoviz.cs.vt.edu/AlgovizWiki//Stacks.
Using a Stack
Topic Tip For more information on using Python list as stacks, read:
www.python.org/doc/2.5.2/tut/node7.html (see Section 5.1.1).
Quick Quiz 1
1. Stacks are said to adhere to a(n) ____________________ protocol (LIFO).
2. How can Python programmers use a Python list to emulate a stack? What is the problem
with this approach?
3. True or False: The stack method pop() returns the item at the top of the stack, but
does not remove it.
4. True or False: Popping an empty stack raises an exception.
Three Applications of Stacks
69
Topic Tip
“Reverse Polish notation (or just RPN) by analogy with the related Polish
notation, a prefix notation introduced in 1920 by the Polish mathematician Jan
Łukasiewicz, is a mathematical notation wherein every operator follows all of its
operands. It is also known as Postfix notation and is parenthesis-free.”
Reference: http://en.wikipedia.org/wiki/Reverse_Polish_notation.
Topic Tip
You can find a good and concise reference on infix and postfix expressions at:
http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-
postfix/index.htm.
Topic Tip More information on converting infix to postfix at:
www.maths.abdn.ac.uk/~igc/tch/mx4002/notes/node72.html.
Topic Tip For an interactive animation of a backtracking algorithm, visit:
www.hbmeyer.de/backtrack/backtren.htm.
Topic Tip
The “queens problem” is another problem that can be solved using a
backtracking algorithm. Find more information at:
http://students.ceid.upatras.gr/~papagel/project/kef5_8.htm.
Topic Tip
Look at more backtracking interactive animations at:
www.hbmeyer.de/backtrack/tableng.htm and
www.hbmeyer.de/backtrack/mag5en.htm.
Topic Tip
For more information on the call stack (also known as a function stack, execution
stack, control stack, or simply the stack), visit:
http://en.wikipedia.org/wiki/Call_stack.
Quick Quiz 2
1. What is the difference between the infix form of an expression and its postfix form?
2. True or False: The postfix expression 4 5 6 * + 3 - evaluates to 34.
3. True or False: The equivalent postfix expression of the infix expression 4 + 5 * 6
- 3 is 4 5 6 * + 3 -.
4. A(n) ____________________ algorithm begins in a predefined starting state and then
moves from state to state in search of a desired ending state.
Implementations of Stacks
70
Topic Tip
You can find an interactive application that illustrates an array-based and a
linked-based implementation of a stack (as well as of other data structures) at:
www.cs.usfca.edu/galles/visualization/download.html.
Topic Tip For more information on linked list implementation of stacks, visit:
www.cs.bu.edu/Topic/c/stack/linked-list/.
Case Study: Evaluating Postfix Expressions
Topic Tip
You can find two online postfix calculators at:
http://main.linuxfocus.org/~guido/javascript/rpnjcalc.html and
www.randomwalking.com/misc/xul_rpn/rpn.xul.
Quick Quiz 3
1. True of False: In our array implementation of a stack, initially, top equals 0.
2. In our array implementation of a stack, initially, ____________________ equals 0.
3. The linked implementation of a stack uses a singly linked sequence of nodes with a
variable top pointing at the list’s ____________________, as well as a variable size
to track the number of items on the stack.
4. With the exception of the ____________________ method, all of the stack methods are
simple and have a maximum running time of O(1).
Additional Resources
1. Python Tutorial: Data Structures:
www.python.org/doc/2.5.2/tut/node7.html
2. Stack (data structure):
http://en.wikipedia.org/wiki/Stack_(data_structure)
3. Stack (computer science):
http://en.wikipedia.org/wiki/Stack_(computer_science)
4. Infix - Postfix:
http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm
5. Reverse Polish Notation:
http://en.wikipedia.org/wiki/Reverse_Polish_notation
71
6. Backtracking:
http://en.wikipedia.org/wiki/Backtracking
7. Call stack:
http://en.wikipedia.org/wiki/Call_stack
Key Terms
activation record: An area of computer memory that keeps track of a function or
method call’s parameters, local values, return value, and the caller’s return address.
ADTs (abstract data types): A class of objects, a defined set of properties of those
objects, and a set of operations for processing the objects.
arithmetic expression: A sequence of operands and operators that computes a value.
backtracking algorithm: A type of algorithm that explores possible paths to a solution
and returns to alternative paths when a given path fails.
decrement: To decrease the value of a variable.
helper: A method or function used within the implementation of a module or class but
not used by clients of that module or class.
infix form: The form of an expression in which the operator is surrounded by its
operands.
instance variable: Storage for data in an instance of a class.
last-in first-out protocol (LIFO): The constraint imposed on access to items in a stack,
whereby the last item inserted is always the first item removed.
linear collection: A collection whose elements have at most one predecessor and at
most one successor.
object heap: An area of computer memory from which storage for objects is allocated.
overflow: In arithmetic operations, a value may be too large for the computer’s memory
location. A meaningless value may be assigned or an error message may result.
postfix form: The form of an expression in which the operator follows its operands.
push: The operation that adds an element to a stack.
run-time environment: Software that supports the execution of a program.
scanning: The process of picking words or tokens out of a stream of characters.
stack(s): A dynamic data structure in which access can be made from only one end.
Referred to as a LIFO (last-in, first-out) structure.
subroutine: A method or a function.
temporary variable: A variable that is introduced in the body of a function or method
for the use of that subroutine only.
token: An individual word or symbol.
top: The end of a stack where elements are added or removed.
72
Python Lesson 9309C Exam
Please complete the following exam. You may use the electronic grading system for quicker
response. Simply log on to www.study-electronics.com and enter your credentials. Once the
exam has been submitted, your results will be returned within 72 hours. You may also e-mail
your answers to [email protected], or fax them to us at 1-216-781-0331. If you have any
questions, please contact the Instruction Department.
Multiple Choice
Identify the choice that best completes the statement or answers the question.
1. The postfix form of the expression 34 * 22 + 2 is ____.
1) 34 22 2 * + 3) 34 22 + 2 *
2) 34 22 2 + * 4) 34 22 * 2 +
2. If we view the end of a list as the top of a stack, the list method ____ removes and returns
the element at its top.
1) pop 3) remove
2) deque 4) delete
3. Assume the current state of a stack s is:
a b c
where c is the top item. What will be the value returned by the operation s.isEmpty()?
1) True 3) An exception will be raised.
2) False 4) c
4. Assume the current state of a stack s is:
a b c
where c is the top item. What will be the state of the stack after the operation s.peek() is
performed?
1) a b 3) a b c
2) b c 4) An exception will be raised.
5. Assume the current state of a stack s is:
a b c
where c is the top item. What will be the value returned by the operation len(s)?
1) 2 3) 4
2) 3 4) An exception will be raised.
6. The load factor for an array implementation of a stack can be as low as ____.
1) 0 3) 1/3
2) 1/4 4) 1/2
73
7. Assume the current state of a stack s is:
a b c
where c is the top item. What will be the state of the stack after the operation s.pop() is
performed?
1) a b 3) a b c
2) b c 4) An exception will be raised.
8. An array implementation is more space-efficient than a linked implementation of a stack
whenever the load factor is greater than ____.
1) 1/4 3) 1/2
2) 1/3 4) 1
9. There are two principal techniques for implementing backtracking algorithms: one uses stacks
and the other uses ____.
1) queues 3) polymorphism
2) lists 4) recursion
10. A ____ algorithm begins in a predefined starting state and then moves from state to state in
search of a desired ending state.
1) backtracking 3) historical
2) translation 4) hierarchical
11. The ____ method of a stack returns the item at the top of the stack, but does not remove it.
1) inspect 3) pop
2) push 4) peek
12. Assuming that an integer and a reference occupy the same amount of space, then the total space
requirement for an array implementation of a stack with n elements and capacity capacity, is
____.
1) capacity 3) capacity + 2
2) 2capacity 4) 2capacity + 2
13. The memory, or run-time environment, controlled by the PVM is divided into ____ regions.
1) four 3) six
2) five 4) seven
14. If we view the end of a list as the top of a stack, the list method ____ pushes an element onto
this stack.
1) push 3) insert
2) append 4) add
15. With the exception of the ____ method, all of the stack methods are simple and have a
maximum running time of O(1).
1) __len__ 3) push
2) __str__ 4) pop
16. The postfix expression 34 22 * 2 + evaluates to ____.
1) 56 3) 112
74
2) 78 4) 750
17. Every time a subroutine is called, an activation record is created and pushed onto the ____.
1) unused memory 3) object heap
2) activation record 4) call stack
18. When an object is instantiated, the PVM must find space for the object on the ____.
1) unused memory 3) object heap
2) activation record 4) call stack
19. The total space requirement for a linked stack of n items is ____.
1) n 3) n + 1
2) 2n 4) 2n + 2
20. The load factor for an array implementation of a stack normally varies between ____ and 1.
1) 1/5 3) 1/3
2) 1/4 4) 1/2
21. The operation for putting items on a stack is called ____.
1) insert 3) push
2) remove 4) pop
22. The postfix expression 34 22 2 * + evaluates to ____.
1) 56 3) 112
2) 78 4) 750
23. Stacks are linear collections in which access is completely restricted to just one end, called the
____.
1) top 3) head
2) bottom 4) tail
24. Assume the current state of a stack s is:
a b c
where c is the top item. What will be the value returned by the operation s.peek()?
1) a 3) c
2) b 4) An exception will be raised.
25. The operation for removing items from a stack is called ____.
1) insert 3) push
2) remove 4) pop
END OF EXAM
75
Chapter 16 - Linear Collections: Lists
LESSON 9310C
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Chapter Notes
Overview
Chapter 16 describes how to use and implement lists. You first learn the difference
between content-based operations, index-based operations, and position-based
operations on lists. Then, you learn about the performance trade-offs between an array-
based implementation and a linked implementation, for both index-based lists and
positional lists. You also learn how to create and use iterators for linear collections.
Finally, a case study describes how to implement a sorted list.
Objectives
After completing this chapter, you will be able to:
Explain the difference between index-based operations on lists and position-based
operations on lists
Analyze the performance trade-offs between an array-based implementation and a
linked implementation of index-based lists
Analyze the performance trade-offs between an array-based implementation and a
linked implementation of positional lists
Create and use an iterator for a linear collection
Develop an implementation of a sorted list
76
Topic Tips
Overview of Lists
Topic Tip
“In computer science, a list is an ordered collection of entities/items. In the
context of object-oriented programming languages, a list is defined as an instance
of an abstract data type (ADT), formalizing the concept of an ordered collection
of entities.”
Reference: http://en.wikipedia.org/wiki/List_(computing).
Topic Tip
You can find a couple of useful animations/simulations of two linked list
implementations at:
www.cosc.canterbury.ac.nz/mukundan/dsal/LinkListAppl.html and
www.cs.stir.ac.uk/~mew/dissertation/simulation.htm.
Quick Quiz 1
1. The first item in a list is at its ____________________, whereas the last item in a list is
at its ____________________.
2. What are indexed-based operations on lists?
3. True or False: Content-based operations usually expect an item as an argument and do
something with it and the list.
4. Position-based operations are performed relative to a currently established position or
____________________ within a list.
Applications of Lists
Topic Tip For more information on hard disk organization, visit:
www.storagereview.com/guide2000/ref/hdd/op/mediaTracks.html.
Indexed List Implementations
Topic Tip
For more information on dynamic arrays, visit:
http://en.wikipedia.org/wiki/Dynamic_array and
www.nist.gov/dads/HTML/dynamicarray.html.
77
Topic Tip
For more information on linked lists, visit:
http://cslibrary.stanford.edu/103/,
http://nist.gov/dads/HTML/linkedList.html, and
http://en.wikipedia.org/wiki/Linked_list.
Topic Tip
“Finding a specific element in a linked list, even if it is sorted, normally requires
O(n) time (linear search). This is one of the primary disadvantages of linked lists
over other data structures. […] In an unordered list, one simple heuristic for
decreasing average search time is the move-to-front heuristic, which simply
moves an element to the beginning of the list once it is found. This scheme,
handy for creating simple caches, ensures that the most recently used items are
also the quickest to find again. Another common approach is to "index" a linked
list using a more efficient external data structure.”
Reference: http://en.wikipedia.org/wiki/Linked_list.
Quick Quiz 2
1. What is the object heap?
2. True or False: A computer’s file system has three major components—a directory of
files, the files themselves, and used space.
3. True or False: ADTs that use lists also inherit their performance characteristics.
4. The complexity of a list’s __getitem__(index) is ____________________ for a
linked implementation.
Iterators
Topic Tip For more information on iterators, visit:
www.python.org/doc/2.5.2/lib/typeiter.html.
Topic Tip
“Lists can be manipulated using iteration or recursion. The former is often
preferred in non-tail-recursive languages, and languages in which recursion over
lists is for some other reason uncomfortable. The latter is generally preferred in
functional languages, since iteration is associated with arrays and often regarded
as imperative.”
Reference: http://en.wikipedia.org/wiki/List_(computing).
78
Topic Tip
“In object-oriented programming, the Iterator pattern is a design pattern in which
iterators are used to access the elements of an aggregate object sequentially
without exposing its underlying representation. An Iterator object encapsulates
the internal structure of how the iteration occurs.”
Reference: http://en.wikipedia.org/wiki/Iterator_pattern.
Topic Tip
“Any user-defined class can support standard iteration (either implicit or explicit)
by defining an __iter__() method which creates an iterator object. The
iterator object then needs to define a next() method which returns the next
element.”
Reference: http://en.wikipedia.org/wiki/Iterator.
Topic Tip
“One way of implementing iterators is using a special kind of subroutine, known
as a generator that can yield values to its caller multiple times (instead of
returning just once). Most iterators are naturally expressible as generators, but
because generators preserve their local state between invocations, they're
particularly well-suited for complicated, stateful iterators, such as tree
traversers.”
Reference: http://en.wikipedia.org/wiki/Iterator.
Quick Quiz 3
1. True or False: We never use a singly linked structure to implement a positional list
because it provides no convenient mechanism for moving to a node’s successor.
2. In a positional list, the purpose of the method ____________________ is to determine
whether the method next can be called to move the cursor to the next item.
3. The running times of all of the methods of a positional list, except for
____________________, in the linked implementation are O(1).
4. What is an iterator?
Case Study: Developing a Sorted List
Topic Tip For other useful problems related to linked lists, visit:
http://cslibrary.stanford.edu/105/.
79
Topic Tip
“A skip list is a probabilistic data structure, based on multiple parallel, sorted
linked lists, with efficiency comparable to a binary search tree (order log n
average time for most operations). Underlying the skip list is an augmentation of
an ordered linked list with additional forward links, added in a randomized way
with a geometric/negative binomial distribution, so that a search in the list may
quickly skip parts of the list (hence the name). Insert, search and delete
operations are performed in logarithmic randomized time.”
Reference: http://en.wikipedia.org/wiki/Skip_list.
Topic Tip
“In computer programming, an unrolled linked list is a variation on the linked
list, which stores multiple elements in each node. It can drastically increase
cache performance, while decreasing the memory overhead associated with
storing list metadata such as references. It is related to the skip list and the B-
tree.”
Reference: http://en.wikipedia.org/wiki/Unrolled_linked_list.
Additional Resources
1. List (computing):
http://en.wikipedia.org/wiki/List_(computing)
2. Dynamic array:
http://en.wikipedia.org/wiki/Dynamic_array
3. Linked list:
http://nist.gov/dads/HTML/linkedList.html
4. Linked list:
http://en.wikipedia.org/wiki/Linked_list
5. Iterator:
http://en.wikipedia.org/wiki/Iterator
6. Iterator Types:
www.python.org/doc/2.5.2/lib/typeiter.html
Key Terms
array(s): A data structure whose elements are accessed by means of index positions.
content-based operation: An operation that involves a search for a given element
irrespective of its position in a collection.
cursor: The pointer in a positional list that locates the item about to be accessed with a
next or a previous operation.
external pointer: A special pointer that allows users to access the nodes in a linked list.
for loop: A structured loop used to traverse a sequence.
80
free list: An area of memory used to allocate storage for objects.
garbage collection: The automatic process of reclaiming memory when the data of a
program no longer need it.
generator object: An object that feeds data items to a user on demand, and is used to
implement iterators.
head: The first element in a list.
heap: An area of computer memory in which storage for dynamic data is available.
Also, a tree that is organized to guarantee logarithmic searches, insertions, and
removals. See also max-heap and min-heap.
index-based operation: An operation that accesses an element by specifying its
position in a collection. For lists, the position is specified as an integer ranging from 0
to the size of the collection minus 1.
iterator: An object that allows clients to navigate a collection by tracking a cursor.
linear collection: A collection whose elements have at most one predecessor and at
most one successor.
position-based operation: An operation performed with respect to a cursor in a
collection.
positional list: A list in which a client navigates by moving a cursor.
sentinel node: A special node in a linked structure that contains no data but instead
marks the beginning or end of the structure.
tail: The last element in a list. Also, an external pointer that is either empty or refers to
the last node in a linked structure.
temporary variable: A variable that is introduced in the body of a function or method
for the use of that subroutine only.
Unified Modeling Language (UML): A graphical notation for describing a software
system in various phases of development.
Continue to the next chapter for the lesson exam
81
Chapter 18 - Hierarchical Collections: Trees
At a Glance
Lesson Contents
Overview
Objectives
Quick Quizzes
Additional Resources
Key Terms
Lesson Assignment
Chapter Notes
Overview
Chapter 18 introduces trees. You learn about the difference between trees and other
types of collections using the relevant terminology. You also learn to recognize
applications for which general trees and binary trees are appropriate. Next, you learn
about the behavior and use of specialized trees (heaps, binary search trees, and
expression trees), and about the performance of binary search trees and heaps. Finally,
you practice developing recursive algorithms to process trees.
Objectives
After completing this chapter, you will be able to:
Describe the difference between trees and other types of collections using the relevant
terminology
Recognize applications for which general trees and binary trees are appropriate
Describe the behavior and use of specialized trees, such as heaps, binary search trees,
and expression trees
Analyze the performance of operations on binary search trees and heaps
82
Develop recursive algorithms to process trees
Topic Tips
An Overview of Trees
Topic Tip
For more information on trees, read:
http://en.wikipedia.org/wiki/Tree_data_structure, and
www.nist.gov/dads/HTML/tree.html.
Topic Tip
Other terms like ordered tree, rooted tree, free tree, and arborescence may also
be used when talking about trees. For more information, visit:
www.nist.gov/dads/HTML/tree.html.
Why Use a Tree?
Topic Tip For more information on search trees, visit:
www.nist.gov/dads/HTML/searchtree.html.
The Shape of Binary Trees
Topic Tip For more binary tree terminology, visit:
http://en.wikipedia.org/wiki/Binary_Tree.
Quick Quiz 1
1. In a tree, each node, except a privileged item called the ____________________, has
exactly one parent.
2. In tree terminology, what is a child?
3. True or False: A heap describes the syntactic structure of a particular sentence in terms
of its component parts, such as noun phrases and verb phrases.
4. A(n) ____________________ binary tree includes a complete complement of nodes at
each level but the last one, is bushy enough to support worst-case logarithmic access to
leaf nodes.
Three Common Applications of Binary Trees
83
Topic Tip
“A binary heap is a heap data structure created using a binary tree. It can be seen
as a binary tree with two additional constraints: (1) The shape property: all levels
of the tree, except possibly the last one (deepest) are fully filled, and, if the last
level of the tree is not complete, the nodes of that level are filled from left to
right; and, (2) The heap property: each node is greater than or equal to each of its
children according to some comparison predicate which is fixed for the entire
data structure.”
Reference: http://en.wikipedia.org/wiki/Binary_heap.
Topic Tip For a useful interactive applet showing how a BST works, visit:
http://people.ksp.sk/~kuko/bak/index.html.
Binary Tree Traversals
Topic Tip
“[The breadth-first order traversal] always attempts to visit the node closest to
the root that it has not already visited. [It is a]lso called a level-order traversal.”
Reference: http://en.wikipedia.org/wiki/Binary_Tree.
Quick Quiz 2
1. What is a min-heap?
2. True or False: The preorder traversal algorithm visits a tree’s root node, and then
traverses the left subtree and the right subtree in a similar manner.
3. Beginning with level ____________________, the level order traversal algorithm visits
the nodes at each level in left-to-right order.
4. In tree terminology, the ____________________ is the set of leaf nodes of a tree.
Developing a Binary Search Tree
Topic Tip For more information on BSTs, read:
http://en.wikipedia.org/wiki/Binary_search_tree.
Topic Tip
For a couple of useful interactive applets showing how BSTs work, visit:
www.cs.jhu.edu/~goodrich/dsa/trees/btree.html, and
www.ibr.cs.tu-bs.de/courses/ss98/audii/applets/BST/BST-Example.html.
84
Implementing Heaps
Topic Tip For a useful interactive applet showing how a heap works, visit:
http://people.ksp.sk/~kuko/bak/index.html.
Quick Quiz 3
1. True or False: An expression tree is never empty.
2. True or False: The array representation of a binary tree is pretty rare and is used mainly
to implement an expression tree.
3. In an array-based heap, the pop operation is O(____________________).
4. When we use a heap to implement a priority queue, items with the highest priority (the
lexically smallest items) are located near the ____________________ of the heap.
Additional Resources
1. Tree (data structure):
http://en.wikipedia.org/wiki/Tree_data_structure
2. Tree:
www.nist.gov/dads/HTML/tree.html
3. Search tree:
www.nist.gov/dads/HTML/searchtree.html
4. Binary tree:
http://en.wikipedia.org/wiki/Binary_Tree
5. Binary heap:
http://en.wikipedia.org/wiki/Binary_heap
Key Terms
binary tree: A tree in which each node has at most two children.
BST (binary search tree): A binary tree in which each node’s left child is less than that
node and each node’s right child is greater than that node.
children: Elements that are directly below a given element in a hierarchical collection.
complete binary tree: A binary tree whose shape is restricted by starting at the root
node and filling the tree by levels from left to right.
85
complexity analysis: The process of deriving a formula that expresses the rate of
growth of work or memory as a function of the size of the data or problem that it solves.
See also big-O notation.
concatenation: An operation in which the contents of one sequence are placed after the
contents of another sequence.
data structure: A compound unit consisting of several data values.
debugging: The process of eliminating errors, or bugs, from a program.
decrement: To decrease the value of a variable.
dequeue: The operation that removes an item from the front of a queue.
edge: A link between two vertices in a graph.
enqueue: The operation that inserts an item at the rear of a queue.
expression tree: A tree in which each leaf node contains a number and each interior
node contains an operator.
frontier: The set of all leaves in a tree.
full binary tree: A binary tree that contains the maximum number of nodes for its
height.
general tree: A tree in which each node can have an arbitrary number of children.
heap: An area of computer memory in which storage for dynamic data is available.
Also, a tree that is organized to guarantee logarithmic searches, insertions, and
removals. See also max-heap and min-heap.
heap property: The relationship that characterizes nodes and their children in a heap,
for example, each node is greater than either of its children.
helper: A method or function used within the implementation of a module or class but
not used by clients of that module or class.
hierarchical collection: A collection whose elements may have zero or more
successors, but at most one predecessor.
inorder traversal: A tree traversal that visits the left child, visits the item, and visits the
right child of each node.
interior node: A node that has at least one child in a tree.
leaf: A node without children.
left child: One of two immediate descendants of a given node in a binary tree.
left subtree: The node and its descendants to the left of a given node in a binary tree.
length of a path: The number of edges needed to reach one vertex from another vertex
in a graph.
level order traversal: A tree traversal that visits each node, from left to right, at a given
level before moving to the next level.
max-heap: A tree in which each node is greater than either of its children.
min-heap: A tree in which each node is less than either of its children.
node: A component of a linked structure, consisting of a data item and one or more
pointers to other nodes.
parse tree: A data structure developed during parsing that represents the structure of a
sentence or expression.
parsing: The process of analyzing an expression for syntactic correctness.
perfectly balanced binary tree: A binary tree in which each level but the last one must
be occupied by a complete set of nodes.
positional list: A list in which a client navigates by moving a cursor.
postorder traversal: A tree traversal that visits the left child, visits the right child, and
visits the item of each node.
86
preorder traversal: A tree traversal that visits the item, visits the left child, and visits
the right child of each node.
right child: One of two immediate descendants of a given node in a binary tree.
right subtree: The node and its descendants to the right of a given node in a binary
tree.
root: The node in a tree that has no predecessor.
singleton pattern: A design pattern in which just a single instance of a given class is
used by all application programs.
sorted collection: A collection whose elements are arranged in sorted order.
87
Python Lesson 9310C Exam
Please complete the following exam. You may use the electronic grading system for quicker
response. Simply log on to www.study-electronics.com and enter your credentials. Once the
exam has been submitted, your results will be returned within 72 hours. You may also e-mail
your answers to [email protected], or fax them to us at 1-216-781-0331. If you have any
questions, please contact the Instruction Department.
Multiple Choice
Identify the choice that best completes the statement or answers the question.
1. The two most critical ____ operations are add and pop.
1) BST 3) expression tree
2) binary tree 4) heap
2. In a tree, a(n) ____ is the line that connects a parent to its child.
1) edge 3) connector
2) leaf 4) rope
3. In a list, the L.append(item) operation is a(n) ____ operation.
1) position-based 3) content-based
2) queue-based 4) index-based
4. The pop method of a heap deletes the ____ node in the heap, returns the element contained
there, and maintains the heap property.
1) bottommost 3) last
2) topmost 4) rightmost leaf
5. The first item in a list is at called ____.
1) top 3) front
2) first 4) head
6. A(n) ____ is never empty.
1) expression tree 3) perfectly balanced binary tree
2) BST 4) complete binary tree
7. A ____ supports manipulation of items at any point within a linear collection.
1) dictionary 3) stack
2) list 4) queue
8. The running time for inserting an item at a preestablished position in a singly linked structure is
____.
1) O(1) 3) O(log n)
2) O(n) 4) O(n2)
9. Each numeric position in a list is called a(n) ____.
1) index 3) reference
2) pointer 4) iterator
88
10. A common implementation of priority queues uses a(n) ____.
1) heap 3) expression tree
2) BST 4) perfectly balanced binary tree
11. In some programming languages, a separate object called a(n) ____ provides the position-based
operations of a list.
1) cursor 3) iterator
2) pointer 4) index
12. A perfectly balanced tree (one with a height of ____) supports logarithmic searches.
1) log(n) 3) n
2) n log(n) 4) n2
13. A ____ includes a complete complement of nodes at each level but the last one and is bushy
enough to support worst-case logarithmic access to leaf nodes.
1) full binary tree 3) BST
2) complete binary tree 4) perfectly balanced binary tree
14. In a ____, any nodes on the last level are filled in from left to right.
1) full binary tree 3) BST
2) complete binary tree 4) perfectly balanced binary tree
15. In a list, the L.next() operation is a(n) ____ operation.
1) navigational 3) content-based
2) linear 4) index-based
16. The total space requirement for the minimal linked implementation of an indexed list is ____.
1) 3n + 2 3) 2n
2) 2n + 3 4) 3n
17. The ____ operation adds item to the tail of the list.
1) attend(item) 3) add(item)
2) append(item) 4) insert(item, 0)
18. When viewed from an index-based perspective, lists are sometimes called ____ or sequences,
and in their use of indices, they are reminiscent of arrays.
1) queues 3) vectors
2) heaps 4) grids
19. In a tree, a(n) ____ is a node that has no children.
1) branch 3) root
2) interior node 4) leaf
20. A(n) ____ is an item stored in a tree.
1) branch 3) node
2) element 4) leaf
21. If a collection provides support for a(n) ____, that collection can be traversed using a Python
for loop.
1) cursor 3) index
2) iterator 4) pointer
89
22. A ____ is the tree formed by considering a node and all its descendants.
1) successor 3) child
2) bush 4) subtree
23. The ____ traversal algorithm visits a tree’s root node, and then traverses the left subtree and the
right subtree in a similar manner.
1) preorder 3) postorder
2) inorder 4) level order
24. A file system’s directory is organized as a(n) ____ collection.
1) hierarchical 3) graph
2) ordered 4) indexed-based
25. The running time of locating the ith item in a singly linked structure is ____.
1) O(1) 3) O(log n)
2) O(n) 4) O(n2)
26. For ____, there is an elegant and efficient array-based representation.
1) perfectly balanced binary trees 3) complete binary trees
2) binary search trees 4) expression trees
END OF EXAM
90
Appendix - Quick Quiz Answers
Chapter 1 Quiz 1
1. Informally, an algorithm is like a recipe. It provides a set of instructions that tells us how to do
something, such as make change, bake bread, or put together a piece of furniture. More
precisely, an algorithm describes a process that ends with a solution to a problem.
2. central processing unit
3. True
4. graphical user interface
Quiz 2 1. Claude Shannon
2. False
3. This prediction states that the processing speed and storage capacity of hardware will
increase and its cost will decrease by approximately a factor of 2 every 18 months.
4. ARPANET
Quiz 3 1. IDLE
2. A shell window contains an opening message followed by the special symbol >>>, called a
shell prompt.
3. False
4. syntax
Chapter 2 Quiz 1
1. iterative
2. A correct program produces the expected output for any legitimate input. 3. True 4. \n
Quiz 2
1. infinite
2. False 3. True 4. associative
Quiz 3
1. Python includes many useful functions, which are organized in libraries of code called
modules.
2. function 3. False 4. from math import *
Chapter 3 Quiz 1
91
1. In a loop, each repetition of the action is known as a pass or an iteration.
2. True 3. False 4. field width
Quiz 2
1. Boolean
2. The if-else statement is the most common type of selection statement. It is also called a two-way selection statement, because it directs the computer to make a choice between two alternative courses of action.
3. False 4. True
Quiz 3
1. Conditional iteration requires that a condition be tested within the loop to determine
whether the loop should continue.
2. entry-control 3. False 4. break
Chapter 4 Quiz 1
1. A data structure is a compound unit that consists of several smaller pieces of data.
2. True 3. False 4. in
Quiz 2
1. All of the number systems we have examined use positional notation—that is, the value
of each digit in a number is determined by the digit’s position in the number. In other
words, each digit has a positional value. The positional value of a digit is determined by
raising the base of the system to the power specified by the position (baseposition)
2. True 3. False 4. object
Quiz 3
1. file
2. False
3. True
4. empty string
Chapter 5 Quiz 1
1. In Python, a list is written as a sequence of data values separated by commas. The
entire sequence is enclosed in square brackets ([ and ]).
2. False
92
3. False
4. A tuple is a type of sequence that resembles a list, except that, unlike a list, a tuple is
immutable. You indicate a tuple literal in Python by enclosing its elements in
parentheses instead of square brackets.
Quiz 2
1. Some of our scripts might be useful enough to package as functions to be used in other
scripts. Moreover, defining our own functions allows us to organize our code in existing
scripts more effectively.
2. True
3. def
4. Boolean
Quiz 3
1. A dictionary organizes information by association, not position. In computer science,
data structures organized by association are also called tables or association lists. In
Python, a dictionary associates a set of keys with data values.
2. False
3. False
4. get
Chapter 6 Quiz 1
1. An abstraction hides detail and thus allows a person to view many things as just one
thing. We use abstractions to refer to the most common tasks in everyday life.
2. True
3. False
4. One popular design strategy for programs of any significant size and complexity is
called top-down design. This strategy starts with a global view of the entire problem
and breaks the problem into smaller, more manageable subproblems—a process known
as problem decomposition. As each subproblem is isolated, its solution is assigned to a
function.
Quiz 2
1. A recursive function is a function that calls itself.
2. definition
3. False
4. At program startup, the PVM reserves an area of memory named a call stack. For each
call of a function, the PVM must allocate, on the call stack, a small chunk of memory
called a stack frame. In this type of storage, the system places the values of the
arguments and the return address for the particular function call. Space for the function
call’s return value is also reserved in its stack frame. When a call returns or completes
its execution, the return address is used to locate the next instruction in the caller’s
code, and the memory for the stack frame is deallocated.
93
Quiz 3
1. A program’s namespace is the set of its variables and their values.
2. True
3. False
4. This means that they can be assigned to variables (as they are when they are defined),
passed as arguments to other functions, returned as the values of other functions, and
stored in data structures such as lists and dictionaries.
Chapter 7 Quiz 1
1. A Turtle graphics toolkit provides a simple and enjoyable way to draw pictures in a
window and gives you an opportunity to run several methods with an object. Turtle
graphics were originally developed as part of the children’s programming language
Logo, created by Seymour Papert and his colleagues at MIT in the late 1960s. The name
is intended to suggest a way to think about the drawing process. Imagine a turtle
crawling on a piece of paper with a pen tied to its tail.
2. instantiation
3. False
4. 255
Quiz 2
1. Fractals are highly repetitive or recursive patterns.
2. False
3. True
4. nested
Quiz 3
1. discrete
2. True
3. nested
4. tuple
Chapter 8 Quiz 1
1. Like functions, objects are abstractions. A function packages an algorithm in a single
operation that can be called by name. An object packages a set of data values—its
state—and a set of operations—its methods—in a single entity that can be referenced
with a name. This makes an object a more complex abstraction than a function. To get
inside a function, you must view the code contained in its definition. To get inside an
object, you must view the code contained in its class. A class definition is like a
blueprint for each of the objects of that class.
2. True
3. False
4. mutators
94
Quiz 2
1. False
2. __mod__
3. Operator overloading is another example of an abstraction mechanism. In this case,
programmers can use operators with single, standard meanings even though the
underlying operations vary from data type to data type.
4. A class variable is visible to all instances of a class and does not vary from instance to
instance. While it normally behaves like a constant, in some situations a class variable
can be modified. But when it is, the change takes effect for the entire class.
Quiz 3
1. Data encapsulation
2. Inheritance
3. Polymorphism is an object-oriented technique that allows several different classes to
use the same general method names.
4. True
Chapter 9 Quiz 1
1. Most modern computer software employs a graphical user interface or GUI. A GUI
displays text as well as small images (called icons) that represent objects such as
directories, files of different types, command buttons, and drop-down menus. In
addition to entering text at the keyboard, the user of a GUI can select an icon with a
pointing device, such as a mouse, and move that icon around on the display. Commands
can be activated by pressing the Enter key or Control keys, by pressing a command
button, or by selecting a drop-down menu item with the mouse. Put more simply, a GUI
displays all information, including text, graphically to its users, and allows them to
manipulate this information directly with a pointing device.
2. widgets
3. False
4. Entry fields are boxes within which the program can output text or receive it as input
from the user.
Quiz 2
1. Tkinter is a Python standard module that includes classes for windows and
numerous types of window objects.
2. tkMessageBox
3. True
4. entry
Quiz 3
1. False
2. The user can resize a (resizable) window by dragging its lower-right corner in any
direction.
95
3. True
4. pane
Chapter 11 Quiz 1
1. One way to measure the time cost of an algorithm is to use the computer’s clock to
obtain an actual run time. This process, called benchmarking or profiling, starts by
determining the time for several different data sets of the same size and then calculates
the average time. Next, similar data are gathered for larger and larger data sets. After
several such tests, enough data are available to predict how the algorithm will behave
for a data set of any size.
2. True
3. False
4. proportionality
Quiz 2
1. min
2. False
3. True
4. binary
Quiz 3
1. Perhaps the simplest strategy is to search the entire list for the position of the smallest
item. If that position does not equal the first position, the algorithm swaps the items at
those positions. It then returns to the second position and repeats this process, swapping
the smallest item with the item at the second position, if necessary. When the algorithm
reaches the last position in this overall process, the list is sorted. The algorithm is called
selection sort because each pass through the main loop selects a single item to be
moved.
2. False
3. n2
4. True
Chapter 13 Quiz 1
1. Data items in hierarchical collections are ordered in a structure reminiscent of an
upside-down tree. Each data item except the one at the top has just one predecessor, its
parent, but potentially many successors, called its children.
2. False
3. abstract data types
4. True
Quiz 2
1. True
96
2. An array’s load factor equals the number of items stored in the array divided by the
array’s capacity. For example, the load factor is 1 when an array is full, 0 when the
array is empty, and 0.33 when an array of ten cells has three of them occupied.
3. False
4. three-dimensional
Quiz 3
1. head
2. False
3. True
4. A circular linked structure contains a link from the last node back to the first node in the
structure. There is always at least one node in this implementation. This node, the
dummy header node, contains no data, but serves as a marker for the beginning and the
end of the linked structure.
Chapter 14 1. last-in first-out
2. If we view the end of a list as the top of a stack, the list method append pushes an
element onto this stack, whereas the list method pop removes and returns the element at
its top. The main drawback of this option is that our stack can be manipulated by all of
the other list operations as well. These include the insertion, replacement, and removal
of an element at any position. These extra operations violate the spirit of a stack as an
ADT.
3. False
4. True
Quiz 2
1. In the infix form, each operator is located between its operands, whereas in the postfix
form, an operator immediately follows its operands.
2. False
3. True
4. backtracking
Quiz 3
1. False
2. size
3. head
4. __str__
Chapter 16 Quiz 1
1. head, tail
2. Index-based operations manipulate items at designated indices within a list. In the case
of array-based implementations, these operations also provide the convenience of
random access.
97
3. True
4. cursor
Quiz 2
1. The object heap is an area of memory from which the Python virtual machine allocates
segments of various sizes for all new data objects. When an object no longer can be
referenced from a program, the PVM can return that object’s memory segment to the
heap for use by other objects.
2. False
3. True
4. O(n)
Quiz 3
1. False
2. hasNext
3. __str__
4. The Python compiler translates the for loop to code that uses a special type of object
called an iterator. An iterator object behaves like a stripped-down version of a positional
list. An iterator allows its user to move to each item in an underlying collection and
examine it
Chapter 18 Quiz 1
1. root
2. A child is a node immediately below and directly connected to a given node. A node
can have more than one child, and its children are viewed as organized in left-to-right
order. The leftmost child is called the first child, and the rightmost is called the last
child.
3. False
4. perfectly balanced
Quiz 2
1. A min-heap is a binary tree in which each node is less than or equal to both of its
children.
2. True
3. 0
4. frontier
Quiz 3
1. True
2. False
3. log n
4. top