Formulating Algorithms Case Study CounterControlled Repetition
To illustrate how algorithms are developed, we solve several variations of a class-averaging problem. Consider the following problem statement A class often students took a quiz. The grades integers in the range 0 -100 for this quiz are available. Determine the class average on the quiz. The class average is equal to the sum of the grades divided by the number of students. The algorithm for solving this problem requests each of the grades, performs the averaging calculation and prints the...
Control Structures 1
Normally, statements in a program are executed in the order in which they are written. This is called sequential execution. Various Python statements enable the programmer to specify that the next statement to be executed may be other than the next one in sequence. This is called transfer of control. Transfer of control is achieved with Python control structures. This section discusses the background of control structure development and the specific tools Python uses to transfer control in a...
Chapter Pqt
The game is reasonably involved. The player could win or lose on the first roll or on any subsequent roll. The variable gameStatus keeps track of the win loss status. Variable gameStatus is one of the strings WON, LOST or CONTINUE. When the player wins the game, gameStatus is set to WON lines 17 and 29 . When the player loses the game, gameStatus is set to LOST lines 19 and 31 . Otherwise, gameStatus is set to CONTINUE, allowing the dice to be rolled again line 21 . If the game is won or lost...
Pseudocode
Pseudocode is an artificial and informal language that helps programmers develop algorithms. Pseudocode consists of descriptions of executable statements those that are executed when the program has been converted from pseudocode to Python. The pseudocode we present here is useful for developing algorithms that will be converted to Python programs. Pseudocode is similar to everyday English it is convenient and user-friendly, although it is not an actual computer programming language. Pseudocode...
Consider The Class Bicycle. Given Your Knowledge Of Some Common Components Of
9.3 Study the inheritance hierarchy of Fig. 9.2. For each class, indicate some common attributes and behaviors consistent with the hierarchy. Add some other classes e.g., UndergraduateStu-dent, GraduateStudent, Freshman, Sophomore, Junior, Senior, etc. to enrich the hierarchy. 9.4 Consider the class Bicycle. Given your knowledge of some common components of bicycles, show a class hierarchy in which the class Bicycle inherits from other classes, which, in turn, inherit from yet other classes....
Formulating Algorithms with TopDown Stepwise Refinement Case Study Nested
Let us work another complete problem. We once again formulate the algorithm using pseudocode and top-down, stepwise refinement and we develop a corresponding Python program. Consider the following problem statement A college offers a course that prepares students for the state licensing exam for real estate brokers. Last year, several of the students who completed this course took the licensing examination. Naturally, the college wants to know how well its students did on the exam. You have...
TERMINOLOGY Vzw
_and_method overloads operator amp built-in function complex contains_method overloads sequence mapping element deletion __div__ method overloads operator divmod_method overloads built-in sequence mapping element retrieval has_key _hex_method overloads built-in _iand_method overloads symbol amp __idiv__ method overloads symbol ifloordiv_method overloads symbol ilshift_method overloads invert_method overloads operator right-hand addition rand__ method overloads right-hand bitwise AND right-hand...
Case Study A Rational Class
Figure 8.9 illustrates a Rational class. The class uses overloaded numerical operators, built-in functions and statements to manipulate rational numbers. A rational number is a fraction represented as a numerator top and a denominator bottom . A rational number can be positive, negative or zero. Class Rational s interface includes a default constructor, string representation method, overloaded abs function, equality operators and several mathematical operators. The class also defines one method...
Internet and World Wide Web Resources Mwv
The World Wide Web Consortium page on CGI is concerned with security issues involving the Common Gateway Interface. This page provides links to CGI specifications, as indicated by the National Center for Supercomputing Applications NCSA . This document provides links to MIME RFCs Request for Comments , MIME related RFCs and other MIME-related information. This is a collection of tutorials and scripts related to CGI. This is the home page of fast CGI an extension to CGI that for high performance...
ANSWERS TO SELFREVIEW EXERCISES Erx
3.1 a multiple-selection. b keywords. c indefinite repetition. d multiplication. e range. f algorithm. g pass. h suite. i the sequence structure, the selection structure, the repetition structure. j flowchart. 3.2 a False. Pseudocode is an artificial and informal language that helps programmers develop algorithms. b True. c False. The if else selection structure is a double-selection structure it selects between two different actions. d False. A fatal logic error causes a program to terminate....
break and continue Statements
Python offers the break and continue statements, which alter the flow of control. The break statement, when executed in a while or for structure, causes immediate exit from that structure. Program execution continues with the first statement after the structure. Figure 3.24 demonstrates the break statement in a for repetition structure. When the if structure detects that x equals 5, it executes the break statement. This terminates the for statement and the program continues with the print...
TERMINOLOGY Atm
action decision model of programming and logical AND operator augmented addition assignment symbol augmented assignment statement augmented assignment symbol break statement compound statement connector symbols continue statement control structure control-structure nesting control-structure stacking counter counter-controlled repetition decision symbol default condition definite repetition double-selection structure diamond symbol dummy value empty statement goto elimination goto statement if...
Functions Bqc
The first namespace that Python searches is the local namespace, which stores bindings created in a block. Function bodies are blocks, so all function parameters and any identifiers the function creates are stored in the function's local namespace. Each function has a unique local namespace one function cannot access the local namespace of another function. In the example above, Python first searches the function's local namespace for an identifier named x. If the function's local namespace...
Augmented Assignment Symbols
Python provides several augmented assignment symbols for abbreviating assignment expressions. For example, the statement can be abbreviated with the augmented addition assignment symbol as c 3 The symbol adds the value of the expression on the right of the sign to the value of the variable on the left of the sign and stores the result in the variable on the left of the sign. Any statement of the form variable variable operator expression where operator is a binary operator, such as , - , , , ,...
Good Programming Practice Dnu
When performing division by an expression whose value could be zero, explicitly test for this case and handle it appropriately in your program such as by printing an error message rather than allowing the fatal error to occur. In chapter 12, we discuss how to write programs that recognize such errors and take appropriate action. This is known as exception handling. In Fig. 3.9 and Fig. 3.12, we included some blank lines in the pseudocode to improve the readability of the pseudocode. The blank...
Functions Afl
Python 2.2b2 26, Nov 16 2001, 11 44 11 MSC 32 bit Intel on Win32 Type help, copyright, credits or license for more information. gt gt gt import math gt gt gt dir '_builtins_', 1_doc_', 1_name_', 'math' lt module math built-in gt '_doc_', 1_name_', 'acos', 'asin', 'atan', 'atan2', ceil, cos, ,cosh,,,el, 'exp', 'fabs', floor, 'fmod', 'frexp', 'hy-pot', 'ldexp', log, llog10,,,modfl, pi, 'pow', sin, 'sinh', 'sqrt', tan, 'tanh' gt gt gt math.sqrt 9.0 3.0
Lists Tuples and Dictionaries Bvk
On the other hand, some types of sequences are immutable they cannot be altered e.g., by changing element values . Python strings and tuples are immutable sequences. For example, if the sequence c were immutable, the statement would be illegal. Let us examine sequence c in detail. The sequence name is c. The length of the sequence is determined by the function call len c . It is useful to know a sequence's length, because referring to an element outside the sequence results in an out-of-range...
Common Programming Error Bqt
Failure to indent all statements that belong to an if suite or an else suite results in a syntax error. The flowchart of Fig. 3.4 illustrates the flow of control in the if else structure. Once again, note that besides small circles and arrows the symbols in the flowchart are rectangles for actions and diamonds for decisions . We continue to emphasize this action decision model of computing. Imagine again a bin containing empty double-selection structures. The programmer's job is to assemble...
if Selection Structure
Selection structures choose among alternative courses of action. For example, suppose that the passing grade on an examination is 60. Then the pseudocode statement If student's grade is greater than or equal to 60 PrintPassed determines whether the condition student's grade is greater than or equal to 60 is true or false. If the condition is true, then Passed is printed, and the next pseudocode statement in order is performed. Remember that pseudocode is not a real programming language. If the...
Displaying Multiple Lines of Text with a Single Statement 1
A single statement can display multiple lines using newline characters. Newline characters are special characters that position the screen cursor to the beginning of the next line. Figure 2.5 outputs four lines of text, using newline characters to determine when to begin each new line. Most of the program is identical to those of Fig. 2.1 and Fig. 2.4, so we discuss only the changes here. Line 4 displays four separate lines of text to the screen. Normally, the characters in a string display...
Common Programming Error Ibc
Confusing the equality operator with the assignment symbol is an error. The equality operator should be read is equal to and the assignment symbol should be read gets, gets the value of or is assigned the value of. Some people prefer to read the equality operator as double equals. In Python, the assignment symbol causes a syntax error when used in a conditional statement. The following example uses six if structures to compare two user-entered numbers. If the condition in any of these if...
StructuredProgramming Summary
Just as architects design buildings by employing the collective wisdom of their profession, so should programmers design their programs. The field of computer programming is younger than architecture, and our collective wisdom is considerably sparser. We have learned that structured programming produces programs that are easier than unstructured programs to understand and hence are easier to test, debug, modify, and even prove correct in a mathematical sense. Figure 3.32 summarizes Python's...
Lists Tuples and Dictionaries Vmc
a 2 0 0 a 2 1 0 a 2 2 0 a 2 3 0 The following nested for structure determines the total of all the elements in sequence a The for structure totals the elements of the sequence one row at a time. The outer for structure iterates over the rows in the table so that the elements of each row may be totaled by the inner for structure. The total is displayed when the nested for structure terminates. The program in Fig. 5.21 performs several other common sequence manipulations on the 3-by-4 list...
Software Engineering Observation Tjb
Many programs can be divided logically into three phases An initialization phase which initializes the program variables a processing phase which inputs data values and adjustspro-gram variables accordingly and a termination phase which calculates and prints the final results. The preceding Software Engineering Observation often is all you need for the first refinement in the top-down process. To proceed to the next level of refinement i.e., the second refinement , we commit to specific...
SELFREVIEW EXERCISES Lnm
8.1 Fill in the blanks in each of the following statements a Special methods_,_and _ through the dot access operator. b Suppose a and b are integer variables and a program calculates the sum a b. Now suppose c and d are string variables and a program performs the concatenation c d. The two operators here are clearly being used for different purposes. This is an example of overloads the operator. _ and_of an operator cannot be changed by over- The print statement implicitly invokes special...
while Repetition Structure
A repetition structure allows the programmer to specify that a program should repeat an action while some condition remains true. The pseudocode statement While there are more items on my shopping list Purchase next item and cross it off my list 26, Nov 16 2001, 11 44 11 MSC 32 bit Intel on copyright, credits or license for more informa- describes the repetition that occurs during a shopping trip. The condition, there are more items on my shopping list is either true or false. If it is true,...
Computer Organization 1
Virtually every computer, regardless of differences in physical appearance, can be envisioned as being divided into six logical units, or sections 1. Input unit. This receiving section of the computer obtains information data and computer programs from various input devices. The input unit then places this information at the disposal of the other units to facilitate the processing of the information. Today, most users enter information into computers via keyboards and mouse devices. Other input...
EXERCISES Hux
3.3 Drivers are concerned with the mileage obtained by their automobiles. One driver has kept track of several tankfuls of gasoline by recording miles driven and gallons used for each tankful. Develop a Python program that prompts the user to input the miles driven and gallons used for each tank-ful. The program should calculate and display the miles per gallon obtained for each tankful. After processing all input information, the program should calculate and print the combined miles per gallon...
Example A Game of Chance
One of the most popular games of chance is a dice game known as craps, which is played in casinos and back alleys throughout the world. The rules of the game are straightforward A player rolls two dice. Each die has six faces. These faces contain 1, 2, 3, 4, 5 and 6 spots. After the dice have come to rest, the sum of the spots on the two upward faces is calculated. If the sum is 7 or 11 on the first throw, the player wins. If the sum is 2, 3 or 12 on the first throw called craps , the player...
Formulating Algorithms with TopDown Stepwise Refinement Case Study
Let us generalize the class-average problem. Consider the following problem Develop a class-averaging program that processes an arbitrary number of grades each time the program is executed. In the first class-average example, the program knows the number of grades 10 to be entered by the user. In this example, no indication is given of how many grades will be entered. The program processes an arbitrary number of grades. How can the program determine when to stop the input of grades How will it...
Introduction Wfs
Before writing a program to solve a particular problem, it is essential to have a thorough understanding of the problem and a carefully planned approach to solving the problem. When writing a program, it is equally essential to understand the types of building blocks that are available and to use proven program-construction principles. In this chapter, we discuss these issues in our presentation of the theory and principles of structured programming. The techniques that you learn are applicable...
Testing and Debugging Tip Jna
When looping through a sequence, the positive sequence subscript should be less than the total number of elements in the sequence i.e., the subscript should not be larger than the length of the sequence whereas, the negative sequence subscript should be equal to or greater than the negation of the total number of elements in the sequence. Make sure the loop-terminating condition prevents accessing elements outside this range. Generally, a program does not concern itself with the length of a...




