## Implementing the Model

So far, we have a pretty good picture of what the Dice class will do and a starting point for implementing the PokerApp class. We could proceed by working on either of these classes. We won't really be able to try out the PokerApp class until we have dice, so let's start with the lower-level Dice class. The Dice class implements a collection of dice, which are just changing numbers. The obvious representation is to use a list of five ints. Our constructor needs to create a list and assign some...

## Definite Loops

You already know that programmers use loops to execute a sequence of statements several times in succession. The simplest kind of loop is called a definite loop. This is a loop that will execute a definite number of times. That is, at the point in the program when the loop begins, Python knows how many times to go around (or iterate) the body of the loop. For example, the Chaos program from Chapter 1 used a loop that always executed exactly ten times. This particular loop pattern is called a...

## Example Program Word Frequency

Let's write a program that analyzes text documents and counts how many times each word appears in the document. This kind of analysis is sometimes used as a crude measure of the style similarity between two documents and is also used by automatic indexing and archiving programs (such as Internet search engines). At the highest level, this is just a multi-accumulator problem. We need a count for each word that appears in the document. We can use a loop that iterates through each word in the...

## Multi Way Decisions

The newest version of the quadratic solver is certainly a big improvement, but it still has some quirks. Here is another example run. This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c) 1, 2, 1 The solutions are -1.0 -1.0 This is technically correct the given coefficients produce an equation that has a double root at -1. However, the output might be confusing to some users. It looks like the program has mistakenly printed the same number twice. Perhaps...

## The Halting Problem

Let's just imagine for a moment that this book has inspired you to pursue a career as a computer professional. It's now six years later, and you are a well-established software developer. One day, your boss comes to you with an important new project, and you are supposed to drop everything and get right on it. It seems that your boss has had a sudden inspiration on how your company can double its productivity. You've recently hired a number of rather inexperienced programmers, and debugging...

## Developing a GUI

Now that we have a working program, let's turn our attention to a nicer graphical interface. Our first step must be to decide exactly how we want our interface to look and function. The interface will have to support the various methods found in the text-based version and will also probably have some additional helper methods. Let's start with the basic methods that must be supported and decide exactly how interaction with the user will occur. Clearly, in a graphical interface, the faces of the...

## Boolean Expressions as Decisions

So far, we have talked about Boolean expressions only within the context of other control structures. Sometimes, Boolean expressions themselves can act as control structures. In fact, Boolean expressions are so flexible in Python that they can sometimes lead to subtle programming errors. Consider writing an interactive loop that keeps going as long as the user response starts with a y. To allow the user to type either an upper or lower case response, you could use a loop like this while...

## Simulating Racquetball A Simulation Problem

Suzie Programmer's friend, Denny Dibblebit, plays racquetball. Over years of playing, he has noticed a strange quirk in the game. He often competes with players who are just a little bit better than he is. In the process, he always seems to get thumped, losing the vast majority of matches. This has led him to question what is going on. On the surface, one would think that players who are slightly better should win slightly more often, but against Denny, they seem to win the lion's share. One...

## Example Multi Sided Dice

You know that a normal die the singular of dice is a cube and each face shows a number from one to six. Some games employ nonstandard dice that may have fewer e.g., four or more e.g., thirteen sides. Let's design a general class MSDie to model multi-sided dice.1 We could use such an object in any number of simulation or game programs. Each MSDie object will know two things. When a new MSDie is created, we specify how many sides it will have, n. We can then operate on the die through three...

## Divide and Conquer Merge Sort

As discussed above, one technique that often works for developing efficient algorithms is the divide-and-conquer approach. Suppose a friend and I were working together trying to put our deck of cards in order. We could divide the problem up by splitting the deck of cards in half with one of us sorting each of the halves. Then we just need to figure out a way of combining the two sorted stacks. The process of combining two sorted lists into a single sorted result is called merging. If you think...

## Towers of Hanoi

One very elegant application of recursive problem solving is the solution to a mathematical puzzle usually called the Tower of Hanoi or Tower of Brahma. This puzzle is generally attributed to the French mathematician Edouard Lucas, who published an article about it in 1883. The legend sorrounding the puzzle goes something like this. Somewhere in a remote region of the world is a monastery of a very devout religious order. The monks have been charged with a sacred task that keeps time for the...

## Example Program Future Value

Let's close the chapter with one more example of the programming process in action. We want to develop a program to determine the future value of an investment. Let's start with an analysis of the problem requirements . You know that money that is deposited in a bank account earns interest, and this interest accumulates as the years pass. How much will an account be worth ten years from now Obviously it depends on how much money we start with the principal and how much interest the account...

## Future Value with a Function

Now that you've seen how defining functions can help solve the code duplication problem, let's return to the future value graph. Recall the problem is that bars of the graph are printed at two different places in the program. The code just before the loop looks like this. Draw bar for initial principal bar Rectangle Point 0, 0 , Point 1, principal And the code inside of the loop is as follows. bar Rectangle Point year, 0 , Point year 1, principal Let's try to combine these two into a single...

## Loop and a Half

Some programmers would solve the warning problem from the previous section using a slightly different style. number input Enter a positive number if x gt 0 break Loop exit print The number you entered was not positive Here the loop exit is actually in the middle of the loop body. This is called a loop and a half. Some purists frown on exits in the midst of a loop like this, but the pattern can be quite handy. The loop and a half is an elegant way to avoid the priming read in a sentinel loop....

## Suppose You Are Doing A Random Walk See Previous Problem On The Blocks Of A City Street

Draw the top levels of a structure chart for a program having the following main function. length, width getDimensions amtNeeded computeAmount length,width printReport length, width, amtNeeded 2. Write an expression using either random or randrange to calculate the following. A random int in the range 0-10 A random float in the range-0.5-0.5 A random number representing the roll of a six-sided die A random number representing the sum resulting from rolling two six-sided dice A random float...

## Interactive Graphics

Graphical interfaces can be used for input as well as output. In a GUI environment, users typically interact with their applications by clicking on buttons, choosing items from menus, and typing information into on-screen text boxes. These applications use a technique called event-driven programming. Basically, the program draws a set of interface elements often called widgets on the screen, and then waits for the user to do something. When the user moves the mouse, clicks a button or types a...

## Python Programming Exercises Ask User For 4 Numbers Absolute Value

Show the result of evaluating each expression. Be sure that the value is in the proper form to indicate its type int, long int, or float . If the expression is illegal, explain why. 2. Translate each of the following mathematical expressions into an equivalent Python expression. You may assume that the math library has been imported via import math . 3. Show the list of numbers that would be generated by each of the following range expressions. 4. Show the output that would be generated by...

## Functions that Return Values

You have seen that parameter passing provides a mechanism for initializing the variables in a function. In a way, parameters act as inputs to a function. We can call a function many times and get different results by changing the input parameters. Sometimes we also want to get information back out of a function. This is accomplished by having functions return a value to the caller. You have already seen numerous examples of this type of function. For example, consider this call to the sqrt...

## Post Test Loop

Suppose you are writing an input algorithm that is supposed to get a nonnegative number from the user. If the user types an incorrect input, the program asks for another value. It continues to reprompt until the user enters a valid value. This process is called input validation. Well-engineered programs validate inputs whenever possible. get a number from the user until number is gt 0 The idea here is that the loop keeps getting inputs until the value is acceptable. The flowchart depicting this...

## Indefinite Loops

Our averaging program is certainly functional, but it doesn't have the best user interface. It begins by asking the user how many numbers there are. For a handful of numbers this is OK, but what if I have a whole page of numbers to average It might be a significant burden to go through and count them up. It would be much nicer if the computer could take care of counting the numbers for us. Unfortunately, as you no doubt recall, the for loop is a definite loop, and that means the number of...

## Certain Cs Professor Gives

Explain the following patterns in your own words. 2. The following is a silly decision structure. a, b, c input 'Enter three numbers ' if a gt b print Spam Please else print It's a late parrot elif b gt c print Cheese Shoppe if a gt c print Cheddar elif a lt b print Gouda elif c b print Larch print Done Show the output that would result from each of the following possible inputs. 3. Many companies pay time-and-a-half for any hours worked above 40 in a given week. Write a program to input the...

## Python Programming Chapter 9 Exercises Zelle

Given the initial statements import string s1 spam s2 ni Show the result of evaluating each of the following string expressions. a The Knights who say, s2 3 2. Given the same initial statements as in the previous problem, show a Python expression that could construct each of the following results by performing string operations on s1 and s2 . c Spam Ni Spam Ni Spam Ni 3. Show the output that would be generated by each of the following program fragments. a for ch in aardvark b for w in...