Chapter 1 – Introduction - Department of Computer Science

Chapter 1 – Introduction
This chapter addresses the question “What is computer science?” We begin by introducing the
essence of computational problem solving via some classic examples. Next, computer
algorithms, the heart of computational problem solving, are discussed. This is followed by a look
at computer hardware (and the related issues of binary representation and operating systems)
and computer software (and the related issues of syntax, semantics and program translation).
The chapter finishes up by presenting the process of computational problem solving, with an
introduction to the Python programming language.
OBJECTIVES
After reading this chapter and completing the exercises, you will be able to:
Explain the essence of computational problem solving
Explain what a computer algorithm is
Explain the fundamental concepts of digital hardware
Explain the role of binary representation in digital computing
Explain what an operating systems is
Explain the fundamental concepts of computer software
To understand the fundamental features of IDLE in Python
Modify and execute a simple Python program
Chapter Overview
The purpose of this chapter is to present students with a broad view of computing, and an
introduction to computational problem solving.
Section 1.1 – What is Computer Science?
At the start of the chapter, students are asked to consider “What is computer science?” They
are told that it is fundamentally about computational problem solving, which leads to the
question of “What is computation?” and to the notion of an algorithm. Therefore, from the
very start, students are provided a view of the field that is not programming-centric.
In section 1.1.1, the Essence of Computational Problem Solving is discussed in terms of the
classic man/cabbage/goat/wolf problem. This particular problem is used for a number of
reasons. First, it is an easy to understand. Second, it is a very good problem for discussing
representation issues, which leads to the notion of abstraction (and modeling). Third, it brings
to light the importance of how a problem is stated – to find a solution, a best (shortest)
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
solution, or all solutions. In this case there are two best solutions, and an infinite number of
solutions overall (if the man rows himself back and forth an arbitrary number of times, for
example). Finally, the method for solving the problem can be scaled up and applied to different
problem domains. This demonstrates the usefulness of general computational methods. A
chapter exercise asks students to think though aspects of this problem. (A program solution to
the man/cabbage/goat/wolf problem is not given in the text. This is left as problem D5 in the
Program Development Problems section of Chapter 11 on recursion.) Next, the calendar month
problem is introduced to make students aware of the importance of algorithms. The point is
made that being a competent programmer is not sufficient for solving this problem without a
provided algorithm. (A specific algorithm for determining the day of the week for a given date is
provided in section 1.2.)
PEDAGOGICAL NOTE: A good class exercise would to be to ask students how a
complete calendar year can be determined by knowing only the day of the week for
January 1st of the given year. A related question would be what algorithms would be
needed in determining and displaying a given calendar year. The answer would be:
A day of the week algorithm (for determining the day for January 1 st)
A leap year algorithm (for determining the number of days in February)
There can be discussion on why determining the number of days in a given month is not
an algorithm (because it does not solve a general problem). The problem of displaying
a complete calendar year is given in Chapter 4.
Section 1.1.2 introduces the Limits of Computational Problem Solving. This points to the
challenges of computing, that it is just not about writing programs, but something much deeper
and more profound. Brute force approaches to both the classic Traveling Salesman Problem
and a chess-playing program are shown to be infeasible. The Traveling Salesman Problem is an
excellent example of how an apparently simple problem is intractable for a small problem size.
The intractability of a perfect chess-playing game is literally discussed in astronomical terms
(that there are more chess games that can be played than the number of atoms in the universe,
or the number of grains of sand it would take to fill the universe solid with sand.)
PEDAGOGICAL NOTE: For the Traveling Salesman Problem, it can be pointed out that
a very good result can be obtained by the simple “nearest neighbor” algorithm (by
starting at any given city and always moving to the nearest next city). It can be
discussed that the result, however, cannot be known to be optimal, and can in some
cases give a result that is much longer than the shortest possible path.
For the problem of chess, it can be said that (human) expert players only think ahead a
few moves, and intuitively know how good the result board would be for them.
Computers, on the other hand, use a lot of computing power to “look ahead” at many
levels of possible moves. Can also discuss the use of heuristics in problem solving (for
example, in general it is better to have a knight near the center of the board rather
than near the edge).
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
2
Section 1.2 – Computer Algorithms
In section 1.2, the notion of an algorithm is introduced. A definition of an algorithm is given in
section 1.2.1 (“What Is an Algorithm?”). The name “algorithm” (as well as the term “algebra”) is
stated as being derived from the ninth-century mathematician Al-Khwarizimi who worked on
“written processes to achieve some goal.” The point is made that a computation is only as good
as its underlying algorithm, and that to be an effective programming requires on understanding
of computer algorithms.
Section 1.2.2 (“Algorithms and Computers: A perfect Match”) makes the point that because
computers and execute instructions quickly and reliable without errors, algorithms and
computers are a perfect match. Algorithms are said to have been used before the existence of
computing machinery, and that they could have been studied further in earlier times. It is
pointed out that the existence of such machines, however, that has motivated this research.
A day of the week algorithm is given in association with the calendar month problem
introduced in section 1.1. Although there are concise formulas for calculating the day of the
week (for any given month, day and year), this method is used as means of introducing a typical
algorithm involving the use of control structures (selection). It is also written to work only for
the year 1800-2099, inclusive, and thus, brings up the notion of valid input.
PEDAGOGICAL NOTE: This algorithm is adapted from an algorithm that appears in The
Lincoln Library of Essential Information, 1937, given below. The algorithm in its original
form serves as a good example of how NOT to write an algorithm. (In particular, note
the use of the “but statement” and the ambiguous “if-else” structures.) This may be
presented and discussed in class before discussion of the modified version of the text. I
always enjoyed telling the class about an episode of MASH in which Hawkeye needed to
disable a bomb, and was being told how to do so over the walkie-talkie. He cut a wire
as he was told (“cut the red wire”) which was followed by “but first ….”. (If I am dating
myself, see episodes on YouTube).
To find the day of the week for any given date between 1800-2099 (from the Lincoln Book of Essential
Knowledge, 1937):
1. Take the last two digits of the number indicating the year. Increase by 1/4 the number formed by
these digits, omitting fractions.
2. If the first two digits of the year number compose 18, add 2; if 19, add 0; if 20, add 6.
3. Add, if Jan. or Oct., 1; May, 2; Aug., 3; Feb., March, or Nov., 4; June, 5; Sept or Dec., 6; April or
July, 0; but, if in a leap year, add, for Jan, 6; Feb, 3.
4. Add day of month.
5. Divide the sum by 7; the remainder gives the number of the day in the week. If there is no
remainder, the day is Saturday.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
3
Section 1.3 – Computer Hardware
Fundamental components of computer hardware are given in section 1.3. Section 1.3.1
provides students with the understanding of the benefits of binary representation. It asks
students to consider digitalization using ten voltage levels (base ten) vs. using only two (binary
representation). The simplicity of binary representation in terms of hardware design and
reliability is understood as being based on the use of “on/off” switches. Transistors are
described as high-speed electronic switches, and integrated circuits are said to consist of
millions, or even billions, of transistors.
Section 1.3.2 gives brief coverage of the binary number system by analogy to base ten. Here is
where bits and bytes are first mentioned and defined. A means of converting values in base ten
to base two is provided. Examples and exercises of adding binary numbers is not seen as very
meaningful for the sake of the concepts conveyed. However, such examples and exercises can
be easily included.
Section 1.3.3 provides a very brief overview of the fundamental hardware components: cpu,
main memory, secondary memory, input/output devices, and busses. Mention of volatile vs.
non-volatile memory is made here.
Section 1.3.4 discusses operating systems as a bridge between hardware and software. An
operating system is said to be an example of system software. It is stated that it is the
operating system, not the particular model computer, that defines the “look and feel” (user
interface) and the means of interacting with a computer.
Section 1.3.5 ends this section on computer hardware with a discussion of Moore’s Law. This is
viewed as a key concept that is simple enough to be understood given the material presented
in this section.
Section 1.4 – Computer Software
Computer software is discussed in section 1.4. Ada Lovelace is presented as “the first computer
programmer.” This introduction of a woman in the field that was so engaged in the notion of
computing (and who had greater vision of its capabilities than Charles Babbage) should make
some impact with female students in particular.
Section 1.4.1 describes computer software as instructions that can take various physical forms.
The definition of application software is given to complement the definition of system software
described in the previous section on operating systems.
Section 1.4.2 presents the notion of the syntax and semantics of languages. This includes
discussion of program translation. The concept of a compiler vs. an interpreter is given (along
with the definition of machine code). The intent is that students have some understanding of
what is behind the interactive nature of Python. Also in this section syntax vs. logic (semantic)
errors are discussed.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
4
Section 1.4.3 gives a very brief mention of procedural (imperative) and object-oriented
programming. Although it is not possible to explain the difference between the two in any
meaningful way at this point, it is worth mentioning. Students therefore are aware that they are
first learning the procedural paradigm of programming and moving to an object-oriented
approach via Chapter 6 (on objects) and Chapter 10 (object-oriented programming).
Section 1.5 – The Process of Computational Problem Solving
This section presents the process of computational problem solving used throughout the rest of
the book. Therefore, it is important that students have a good grasp of this material. The
process of computational problem solving is described as having four steps: Analysis, Design,
Implementation, and Testing. The problems introduced at the start of the chapter
(Man/Cabbage/Goat/Wolf problem, the Traveling Salesman Problem, and a chess-playing
program) are discussed in terms of each of these four steps.
PEDAGOGICAL NOTE: It is worth emphasizing the need for testing early. Can give
examples of software errors with serious consequences. One example is the embedded
system of the Therac-25 radiation therapy machine in the 1980s (see
http://en.wikipedia.org/wiki/Therac-25). Another is the single software error that
brought down the AT&T long distance network in 1990. More examples can be found at
http://en.wikipedia.org/wiki/List_of_software_bugs.
Section 1.5.1 discusses the first step of computational problem solving – the problem analysis
phase. This is described as first understanding the problem, then considering what constitutes a
solution (a solution, an approximate solution, a best solution and all solutions). The MCGW
problem is said to have an infinite number of solutions, and two best (shortest) solutions. The
Traveling Salesman Problem is said to have only one best solution (the shortest). And the chess
playing is said to have a number of solutions comparable to the number of possible games that
can be played (discarding the consideration that a win with less number of moves than another
win is a better solution).
Section 1.5.2 discusses the second step of computational problem solving – describing the
needed data, and describing the needed algorithms. The description is in terms of data
structures needed (without introduction the term “data structure.”) The data for the MCGW
program is presented as a list. The data for the calendar month problem is shown as
incorporating a few lists (and the use of integers for representing the days of the week). The
Traveling Salesman Problem is shown to use a table. Finally, the chess playing problem is shown
as a two-dimensional grid represented in two different ways: by each grid location containing a
letter representing the type of chess piece (e.g., P for pawn), and using positive and negative
values (discussed as a better representation). This causes students to understand that there is
generally more than one way to represent a problem, and there are advantages and
disadvantages of each that can be considered in terms of which is most effective from a
computational point of view.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
5
The needed algorithms are discussed for each of these problems. For the MCGW problem, a
standard search algorithm, “brute-force” approach suffices. For the calendar month problem,
the previously discussed day of the week and leap year algorithms are needed. For the
Traveling Salesman Problem (in which a brute-force approach is infeasible to use) the existence
of various non-trivial algorithms for its solution, for tens of thousands of cities is mentioned.
Here the notion of a heuristic algorithm is given as methods that work well in general but are
not guaranteed to give correct, or “near correct” solutions for any given problem instance.
Section 1.5.3 describes the difference between the description of data and algorithms and their
realization. The implementation details are said to include the particular programming language
used, and the details of the program implementation of the needed data and algorithms.
Section 1.5.4 discusses program testing as a crucial and unavoidable part of program
development. Program errors are said to be pervasive, persistent and inevitable (referred to as
“truisms” of software development). In addition the to importance of correcting errors, the
point is made that it is also very important to understand WHY particular changes made in a
program corrects a particular error (or set of errors). If the result of a correction is not
understood, then it is stated that the programmer has lost control of the program logic. Thus, a
change may have corrected an error, and caused others. (An example is given as to why a
discrepancy of only 1 cent found by an accountant in reconciling a balance might be the result
of two large errors, and therefore must be resolved.)
Section 1.6 – The Python Programming Language
This section provides a gentle introduction to the IDLE development environment and the
Python programming language. Section 1.6.1 provides perspective on Python – who developed
it and some examples of where it is used. Section 1.6.2 introduces the IDLE IDE as containing an
editor, translator (Python interpreter) and a program debugger. The Python shell is
demonstrated. Section 1.6.3 give a brief description of the Python Standard Library (as a
collection of built-in modules). Only the import modulename form of import is given at this
point. (Other forms of import are given in Chapter 7 on Module Design.)
Section 1.6.4 introduces Python, just enough (variables, arithmetic operators, basic input and
output) to write a simple straight-line program. Section 1.6.5 gives an example of using IDLE for
the development of a simple program that prompts the user for their first name, and displays a
greeting.
Section 1.7 – A First Program – Calculating the Drake Equation
Section 1.7 presents the first example of computational problem solving in the text calculating
the Drake Equation (described in section 1.7.1). The program calculates the estimated number
of intelligent civilizations that we may be able to communicate with for selected values of
various factors, such as the estimated percentage of stars that have planets, and the
percentage
of
those
that
go
on
to
develop
intelligent
life.
(See
http://en.wikipedia.org/wiki/Drake_equation). In this example comment statements are first
introduced.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
6
In sections 1.72-1.75 the problem is addressed using the four step computational problemsolving approach given in the chapter – problem analysis, program design, program
implementation, and program testing. In this discussion of program testing the notion of a test
case and test plan is first presented. Calculated results for various values of the Drake Equation
are given.
PEDAGOGICAL NOTE: Although the program debugger in IDLE is mentioned, there is no
coverage in the text of the use of this, or any other program debugger. This is because of
the existence of available alternative debuggers that individual instructors may wish to
utilize.
SOLUTIONS TO CHAPTER EXERCISES
Section 1.1
1. Search online for two computing-related fields named “computational X” other than the ones listed
in Figure 1-1.
Possible fields: computational linguistics, computational statistics, computational mechanics,
computational neuroscience, computational engineering
2. Search online for two areas of computer science other than those given in the chapter.
Other possible fields: computer algorithms, operating systems, parallel computing,
distributed computing, theory of computation, information
3. For the Man, Cabbage, Goat, Wolf problem:
(a) List all the invalid states for this problem, that is, in which the goat is left alone with the
cabbage, or the wolf is left alone with the goat.
[E, W, W, W, W]
[E, W, W, E]
[E, E, W, W]
[W, E, E, E]
[W, E, E, W]
[W, W, E, E]
- man leaves cabbage, goat and wolf alone
- man leaves goat and cabbage alone
- man leaves goat and wolf alone
(b) Give the shortest sequence of steps that solves the MCGW problem.
Two possible solutions:
Solution 1:
man rows goat, man rows back alone, man rows cabbage across, man takes goat back, man
leaves goat and rows wolf across, man rows back alone, man rows goat across.
Solution 2:
man rows goat, man rows back alone, man rows wolf across, man takes goat back, man
leaves goat and rows cabbage across, man rows back alone, man rows goat across.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
7
(c) Give the sequence of state representations that correspond to your solution starting with
(E,E,E,E) and ending with (W,W,W,W).
Solution 1:
[E,E,E,E] [W,E,W,E] [E,E,W,E] [W,W,W,E] [E,W,E,E] [W,W,E,W], [E,W,E,W] [W,W,W,W]
Solution 2:
[E,E,E,E] [W,E,W,E] [E,E,W,E] [W,E,W,W] [E,E,E,W] [W,W,E,W], [E,W,E,W] [W,W,W,W]
(d) There is an alternate means of representing states. Rather than a sequence representation, a set
representation can be used. In this representation, if an item is on the east side of the river, its
symbol is in the set, and if on the west side, the symbol is not in the set as shown below,
{M,C,G,W}—all items on east side of river (start state)
{C,W}—cabbage and wolf on east side of river, man and goat on west side
{ }—all items on the west side of the river (goal state)
Give the sequence of states for your solution to the problem using this new state
representation.
Solution 1:
{M,C,G,W} {C,W} {M,C,W} {W} {M,G,W} {G}, {M,G} { }
Solution 2:
{M,C,G,W} {C,W} {M,C,W} {C} {M,C, G} {G}, {M,G} { }
(e) How many shortest solutions are there for this problem? Two
4. For a simple game that starts with five stones, in which each player can pick up either one or two
stones, the person picking up the last stone being the loser,
(a) Give a state representation appropriate for this problem.
The states can be simply by a tuple containing a single integer (in the range 0-5) and
the current player:
[<player number> <num stones remaining>]
e.g, [1, 3] - player one’s turn with three stones remaining
(b) Give the start state and goal state for this problem.
Start state: [1, 5] – player one goes first starting with five stones
Goal state: [n, 0] – where n is the winning player
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
8
(c) Give a sequence of states in which the first player wins the game.
[1, 5]
[2, 3]
[1, 2]
[2, 1]
[1, 0]
- start state
- result of player 1 picking up two stones
- result of player 2 picking up one stone
- result of player 1 picking up one stone
- result of player 2 picking up one stone (WIN for player 1)
Section 1.2
5. Using the algorithm in Figure 1-8, show all steps for determining the day of the week for January 24
2018. (Note that 2018 is not a leap year.)
1.
2.
3.
4.
5.
6.
7.
century_digits = 20
year_digits = 18
value = 18 + floor(18/4) = 18 + 4 = 22
value = 22 + 6 = 28 (for century equal to 20)
value = 28 + 1 = 29 (for month of January)
value = (29 + 24) mod 7 = 53 mod 7 = 4 (for the day of the month)
for value = 4, day of the week is a Wednesday
6. Using the algorithm in Figure 1-8, determine the day of the week that you were born on.
7. Suppose that an algorithm was needed for determining the day of the week for dates that only
occur within the years 2000–2099. Simplify the day of the week algorithm in Figure 1-8 as much as
possible by making the appropriate changes.
8. As precisely as possible, give a series of steps (an algorithm) for doing long addition
Section 1.3
9. What is the number of bits in 8 bytes, assuming the usual number of bits in a byte?
8 bits
10. Convert the following values in binary representation of base 10. Show all steps.
(a) 1010
(a)
(b)
(c)
(d)
(b) 1011
(c) 1000
(d) 1111
1010 = (0 * 1) + ( 1 * 2) + ( 0 * 4) +( 1 * 8) = 10
1011 = 1010 + 1 = 10 + 1 = 11
1000 = 1 * 8 = 8
1111 = 10000 – 1111 = 16 – 1 = 15
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
9
11. Convert the following values into binary (base 2) representation. Show all steps.
(a) 5
(f) 33
(b) 7
(g) 64
(c) 16
(h) 63
(d) 15
(i) 128
(e) 32
(j) 127
(a) 5 /2 = 2,
2 /2 = 1,
1/2 = 0,
with remainder 1
with remainder 0
with remainder 1
therefore, 5 in binary equals 101
(b) 7/2 = 3,
3/2 = 1,
1/2 = 0,
with remainder 1
with remainder 1
with remainder 1
therefore, 5 in binary equals 111
(c)
16/2 = 8,
8/2 = 4,
4/2 = 2,
2/2 = 1,
1/2 = 0,
with remainder 0
with remainder 0
with remainder 0
with remainder 0
with remainder 1
therefore, 16 in binary equals 10000
(d) 15/2 = 7,
7/2 = 3,
3/2 = 1,
1/2 = 0,
with remainder 1
with remainder 1
with remainder 1
with remainder 1
therefore, 15 in binary equals 1111
(e) 32/2 = 16,
16/2 = 8,
8/2 = 4,
4/2 = 2,
2/2 = 1,
1/2 = 0,
with remainder 0
with remainder 0
with remainder 0
with remainder 0
with remainder 0
with remainder 1
therefore, 32 in binary equals 100000
(f)
33/2 = 16,
16/2 = 8,
8/2 = 4,
4/2 = 2,
2/2 = 1,
1/2 = 0,
with remainder 1
with remainder 0
with remainder 0
with remainder 0
with remainder 0
with remainder 1
therefore, 33 in binary equals 100001
(g) 64/2 = 32,
32/2 = 16,
16/2 = 8,
8/2 = 4,
4/2 = 2,
2/2 = 1,
1/2 = 0,
with remainder 0
with remainder 0
with remainder 0
with remainder 0
with remainder 0
with remainder 0
with remainder 1
therefore, 64 in binary equals 1000000
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
10
(h) 63/2 = 31,
31/2 = 15,
15/2 = 7,
7/2 = 3,
3/2 = 1,
1/2 = 0
with remainder 1
with remainder 1
with remainder 1
with remainder 1
with remainder 1
with remainder 1
therefore, 63 in binary equals 111111
(i)
128/2 = 64
64/2 = 32,
32/2 = 16,
16/2 = 8,
8/2 = 4,
4/2 = 2,
2/2 = 1,
1/2 = 0,
with remainder 0
with remainder 0
with remainder 0
with remainder 0
with remainder 0
with remainder 0
with remainder 0
with remainder 1
therefore, 128 in binary equals 10000000
(j)
127/2 = 63
63/2 = 31,
31/2 = 15,
15/2 = 7,
7/2 = 3,
3/2 = 1,
1/2 = 0
with remainder 1
with remainder 1
with remainder 1
with remainder 1
with remainder 1
with remainder 1
with remainder 1
therefore, 127 in binary equals 1111111
12. What is in common within each of the following groups of binary numbers?
(a) values that end with a “0” digit (e.g., 1100). Each an even number.
(b) values that end with a “1” digit (e.g., 1100). Each an odd number1.
(c) values with a leftmost digit of “1,” followed by all “0s” (e.g., 1000). Each a power of 2.
(d) values consisting only of all “1” digits (e.g., 1111). Each a power of 2 minus 1.
13. Assuming that Moore’s Law continues to hold true, where n is the number of transistors that can
currently be placed on an integrated circuit (chip), and k*n is the number that can be placed on a
chip in eight years, what is the value of k?
Since Moore’s Law states that the number of transistors that can be placed on a chip doubles
roughly every two years, in eight years the increase in the number of transistor would be 24 = 16.
Section 1.4
14. Give two specific examples of an application program besides those mentioned in the chapter.
Productivity software (e.g., word processing and spreadsheet programs), financial software (e.g.,
tax preparation programs, software for an ATM), business software (e.g., workflow management
programs, airline reservation system), information providing software (e.g., geographic information
systems, web search engines), media software (e.g., MP3 player, video editing program), gaming
software (e.g., video games)
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
11
15. For each of the following statements in English, indicate whether the statement contains a syntax
error, a logic (semantic) error, or is a valid statement.
(a) Witch way did he go?
(b) I think he went over their.
(c) I didn’t see him go nowhere.
semantic error
semantic error
semantic error
16. For each of the following arithmetic expressions for adding up the integers 1 to 5, indicate whether
the expression contains a syntax error, a semantic error, or is a valid expression.
(a) 1 + 2 ++ 3 + 4 + 5
(b) 1 + 2 + 4 + 5
(c) 1 + 2 + 3 + 4 + 5
(d) 5 + 4 + 3 + 2 + 1
syntax error
semantic (logic) error
valid
valid
17. Give one benefit of the use of a compiler, and one benefit of the use of an interpreter.
Complied programs generally execute faster than interpreted one.
Interpreters allow for the immediate execution of instructions, useful for program development
and testing.
Section 1.5
18. Use the Python Interactive Shell to calculate the number of routes that can be taken for the
Traveling Salesman problem for:
(a)
(b)
(c)
(d)
6 cities
12 cities
18 cities
36 cities
6! = 720
12! = 479,001,600
18! = 6,402,373,705,728,000
36! = 371,993,326,789,901,217,467,999,448,150,835,200,000,000
19. Enter the following statement into the Python shell:
print('What is your favorite color? ')
What is your favorite color?
Record the output. Now enter the following statement exactly as given:
printt('What is your favorite color? ')
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
12
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
printt('What is your favorite color? ')
NameError: name 'printt' is not defined
>>>
Record the output. Is this a syntax error or a logic error? Syntax error
20. For the Traveling Salesman problem,
(a) Update the list representation of the distances between cities in the table in Figure 1-23 to add
the city of Seattle. The distances between Seattle and each of the other cities is given below.
Atlanta to Seattle, 2641 miles, Boston to Seattle, 3032 miles, Chicago to Seattle, 2043 miles,
LA to Seattle, 1208 miles, NYC to Seattle, 2832 miles, San Francisco to Seattle, 808 miles.
Atlanta
Atlanta
-
Boston
-
Chicago
-
Boston
1110
-
-
-
-
-
-
Chicago
718
992
-
-
-
-
-
2175
2991
2015
-
-
-
-
New York City
888
215
791
2790
-
-
-
San Francisco
2473
3106
2131
381
2901
-
-
Seattle
2641
3032
2043
1208
2832
808
-
Los Angeles
Los Angeles
-
New York City San Francisco Seattle
-
(b) Determine a reasonably short route of travel for visiting each city only once, starting with
Altanta and ending in San Francisco.
Traveling to the next nearest city each time, leaving San Francisco for last:
Atlanta, Chicago, New York City, Boston, San Francisco, Seattle (total of 5638 miles)
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
13
Section 1.6
21. Which of the following capabilities does an integrated development environment (IDE) provide?
(a) Creating and modifying programs
(b) Executing programs
(c) Debugging programs
(d) All of the above
22. The Python shell is a window in which Python instructions are executed? (TRUE/FALSE)
23. Suppose that the math module of the Python Standard Library were imported. What would be the
proper syntax for calling a function in the math module named sqrt to calculate the square root of
four?
math.sqrt(4)
24. What is the value of variable n after the following instructions are executed?
j = 5
k = 10
n = j * k
n would have the value 50
25. Which of the following is a proper arithmetic expression in Python?
(a) 10(15 + 6)
(b) (10 * 2) (4 + 8)
(c) 5 * (6 – 2)
26. Exactly what is output by the following if the user enters 24 in response to the input prompt?
age = input('How old are you?: ')
print('You are', age, 'years old')
You are 24 years old
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
14
SOLUTIONS TO PYTHON PROGRAMMING EXERCISES
P1. Write a simple Python program that displays the following powers of 2, one per line:
21, 22, 23, 24, 25, 26, 27, 28
# Calculating powers of 2
print(2**1, 2**2, 2**3,
2**4,
2**5,
2**6,
2**7,
2**8)
P2. Write a Python program that allows the user to enter any integer value, and displays the value of
two raised to that power. Your program should function as shown below.
What power of two? 10
Two to the power of 10 is 1024
# Calculating power of 2 entered by user
exponent = int(input('What power of two? '))
print('Two to the power of', exponent, 'is', 2**exponent)
P3. Write a Python program that allows the user to enter any integer base and integer exponent, and
displays the value of the base raised to that exponent. Your program should function as shown
below.
What case? 10
What power of 10? 4
10 to the power of 4 is 10000
# Calculating a given base to a given power
base = int(input('What base? '))
exponent = int(input('What power of ' + str(base) + '? '))
print(base, 'to the power of', exponent, 'is', base**exponent)
NOTE:
At this point, students do not know how to concatenate strings to create the input prompt string as
specified in the problem. This was unintentional, and thus needs to be pointed out to students.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
15
P4. Write a Python program that allows the user to enter a four-digit binary number and displays the
value in base 10. Each binary digit should be entered one per line, starting with the leftmost digit, as
shown below.
Enter leftmost digit: 1
Enter the next digit: 0
Enter the next digit: 0
Enter the next digit: 1
The value is 9
# Conversion of binary to base 10
digit1
digit2
digit3
digit4
=
=
=
=
int(input('Enter
int(input('Enter
int(input('Enter
int(input('Enter
leftmost
the next
the next
the next
digit:
digit:
digit:
digit:
'))
'))
'))
'))
value = (digit1 * 8) + (digit2 * 4) + (digit3 * 2) + digit4
print('the value is', value)
P5. Write a simple Python program that prompts the user for a certain number of cities for the
Traveling Salesman problem, and displays the total number of possible routes that can be taken,
Your program should function as shown below.
How many cities?
10
For 10 cities, there are 3628800 possible routes
# Calculating number of routes for the Traveling Salesman problem
import math
num_cities = int(input('How many cities? '))
num_routes = math.factorial(num_cities)
print('For',num_cities,'cities,there are',num_routes,'possible routes')
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
16
SOLUTIONS TO PROGRAM MODIFICATION PROBLEMS
M1. Hello Program: Addition of Entry of First Name
Modify the sample “hello” Python program in section 1.6.5 to first request the user’s first name,
and then request their last name. The program should then display,
Hello firstname lastname
Welcome to Python!
for the firstname and lastname entered.
# My First Python Program
# MODIFICATION: Input and display of first and last name
first_name = input('What is your first name? ')
last_name = input('What is your last name? ')
print('Hello', first_name, last_name)
print('Welcome to Python!')
What is your first name? John
What is your last name? Smith
Hello John Smith
Welcome to Python!
>>>
M2. Drake’s Equation Program: Best Case Calculation
Modify the Drake’s Equation Program from section 1.7 so that it calculates results for a best case
scenario, that is, so that factors p (percentage of stars that have planets), f (percentage of those
planets that develop life), i (percentage of those planets that develop intelligent life), and c
(percentage of those planets that can communicate with us) are all hard-coded as 100%. The value
of R should remain as 7. Design the program so that the only values that the user is prompted for
are how many planets per star can support life, n, and the estimated number of years civilizations
last. Develop a set of test cases for your program with the included test results.
#
#
#
#
#
#
#
#
#
SETI Program
MODIFICATION: Best case scenario
The Drake equation, developed by Frank Drake in the 1960s, attempts to
estimate how many extraterrestrial civilizations, N, may exist in our
galaxy at any given time that we might come in contact with,
N = R * p * n * f * i * c * L
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
17
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
where,
R ...estimated rate of star creation in our galaxy
p ...estimated percent of stars that have planets
n ...estimated average number of planets that can potentially support
life for each star with planets
f ...estimated percent of those planets that actually go on to develop life
i ...estimated percent of those planets go on to develop intelligent life
c ...estimated percent those that are willing and able to communicate
L ...estimated expected lifetime of such civilizations
Given that the value for R, 7 per year. is the least disputed of the
values, it assigned in the program. In addition, the best case (100%) valus
are assigned for factors p, f, i, and c. The user is prompted to enter the
remaining two factors: c and L. The estimated number of civilizations that
may be detected in our galaxy will then be displayed.
---------------------------------------------------------------------------
# display program welcome
print('Welcome to the SETI program')
print('This program will allow you to enter specific values related to')
print('the likelihood of finding intelligent life in our galaxy. All')
print('percentages should be entered as integer values, e.g., 40 and not .40')
print()
#
p
f
i
c
set factors p, f, i, and c to 100 percent
= 100
= 100
= 100
= 100
# get user input for n and L
n = int(input('How many planets per star do you think can support life?: '))
L = int(input('Number of years you think civilizations last?: '))
# calculate result
num_detectable_civilizations = 7 * (p/100) * n * (f/100) * (i/100) * (c/100) * L
# display result
print()
print('Based on the values entered ...')
print('there are an estimated', round(num_detectable_civilizations),
'potentially detectable civilizations in our galaxy')
Welcome to the SETI program
This program will allow you to enter specific values related to
the likelihood of finding intelligent life in our galaxy. All
percentages should be entered as integer values, e.g., 40 and not .40
How many planets per star do you think can support life?: 1
Number of years you think civilizations last?: 10000
Based on the values entered ...
there
are
an
estimated
70000
potentially
detectable
civilizations
in
our
galaxy
>>>
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
18
SOLUTIONS TO PROGRAM DEVELOPMENT PROBLEMS
D1. Estimation of Number of Years to Solve Traveling Salesman Problem of Given Size
Develop and test a program that allows the user to enter an integer value indicating the number of
cities to solve for the Traveling Salesman problem. The program should then output the number of
years it would take to solve using a brute-force approach. Make use of the factorial function of the
math module as shown in Figure 1-28. Estimate the total amount of time it takes by using the
assumptions given in section 1.1.2.
#
#
#
#
#
Number of Years to Solve the Traveling Salesman Problem
This program determines the estimated number of years it would take to
solve the Traveling Salesman problem for a given number of cities, with
the assumption that one million routes be second can be computed.
import math
# Determine number of seconds per year
secs_in_year = 60 * 60 * 24 * 365
# Get number of cities
num_cities = int(input('Enter the number of cities: '))
# Calculate time
time_to_solve = (math.factorial(num_cities) / 10**6) / secs_in_year
# Output Result
print('Time time it would take to solve the Traveling Salesman problem')
print('of', num_cities, 'cities is approximately', time_to_solve, 'years')
Enter the number of cities: 100
Time time it would take to solve the Traveling Salesman problem
of 100 cities is approximately 2.959354878359467e+144 years
>>>
D2. Estimation of Number of Years for All Possible Chess Games to be Played
Based on the information provided about the game of chess in section 1.1.2, develop and test a
program that determines how many years it would take for all possible chess games to be played if
everyone in the world (regardless of age) played one (unique) chess game a day. Assume the
current world population to be 7 billion.
#
#
#
#
#
#
#
Number of Years to Play all Possible Chess Games
This program determines the estimated number of years it would take for
all possible chess games to be played assuming that everyone in the
world played on unique chess game per day (with an assumed world population
of 7 billion people). The number of possible chess games is estimated to
be about 10**120.
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
19
# Set assumed values
number_chess_games = 10**120
number_people_world = 7 * (10**9)
# Calculate time to play all games
time_to_play = number_chess_games / (number_people_world * 365)
# Output Result
print('The number of years it would take for all the possible chess games')
print('to be played if everyone in the world played one unique games per')
print('day is', time_to_play)
The number of years it would take for all the possible chess games
to be played if everyone in the world played one unique games per
day is 3.913894324853229e+107
>>>
Introduction to Computer Science Using Python – Dierbach
Copyright 2013 John Wiley and Sons
20