The String Data Type

A string is a sequence of characters. In Chapter 2 you learned that a string literal is a sequence of characters in quotations. Python also allows strings to be delimited by single quotes apostrophes . There's no difference just be sure to use a matching set. Strings can be stored in variables, just like numbers. Here are some examples illustrating these two forms of string literals. gt gt gt strl Hello gt gt gt str2 'spam' gt gt gt print strl, str2 Hello spam gt gt gt type strl lt type...

A TextBased UI

In designing PokerApp we have also developed a specification for a generic Pokerlnterface class. Our interface must support the methods for displaying information setMoney, setDice, and showResult. It must also have methods that allow for input from the user wantToPlay, and chooseDice. These methods can be implemented in many different ways, producing programs that look quite different even though the underlying model, PokerApp, remains the same. Usually, graphical interfaces are much more...

Exercises

1. Compare and contrast the following pairs of concepts from the chapter. c Programming Language vs. Natural Language d High-Level Language vs. Machine Language 2. List and explain in your own words the role of each of the five basic functional units of a computer depicted in Figure 1.1. 3. Write a detailed algorithm for making a peanut butter and jelly sandwich or some other simple everyday activity . 4. As you will learn in a later chapter, many of the numbers stored in a computer are not...

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...

Simulation and Design

You may not realize it, but you have reached a significant milestone in the journey to becoming a computer scientist. You now have all the tools to write programs that solve interesting problems. By interesting, I mean problems that would be difficult or impossible to solve without the ability to write and implement computer algorithms. You are probably not yet ready to write the next great killer application, but you can do some nontrivial computing. One particularly powerful technique for...

Naive Sorting Selection Sort

Let's start with a simple be the computer approach to sorting. Suppose you have a stack of index cards, each with a number on it. The stack has been shuffled, and you need to put the cards back in order. How would you accomplish this task There are any number of good systematic approaches. One simple method is to look through the deck to find the smallest value and then place that value at the front of the stack or perhaps in a separate stack . Then you could go through and find the smallest of...

For Loops A Quick Review

You already know that the Python for statement provides a kind of loop. It allows us to iterate through a sequence of values. for lt var gt in lt sequence gt lt body gt The loop index variable var takes on each successive value in the sequence, and the statements in the body of the loop are executed once for each value. Suppose we want to write a program that can compute the average of a series of numbers entered by the user. To make the program general, it should work for any size set of...

Comparing Sorts

Now that we have developed two sorting algorithms, which one should we use Before we actually try them out, let's do some analysis. As in the searching problem, the difficulty of sorting a list depends on the size of the list. We need to figure out how many steps each of our sorting algorithms requires as a function of the size of the list to be sorted. Take a look back at the algorithm for selection sort. Remember, this algorithm works by first finding the smallest item, then finding 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...

Objects and Graphics

So far we have been writing programs that use the built-in Python data types for numbers and strings. We saw that each data type could represent a certain set of values, and each had a set of associated operations. Basically, we viewed the data as passive entities that were manipulated and combined via active operations. This is a traditional way to view computation. To build complex systems, however, it helps to take a richer view of the relationship between data and operations. Most modern...

File Loops

One disadvantage of all the averaging programs presented so far is that they are interactive. Imagine you are trying to average 87 numbers and you happen to make a typo near the end. With our interactive program, you will need to start all over again. A better approach to the problem might be to type all of the numbers into a file. The data in the file can be perused and edited before sending it to a program that generates a report. This file-oriented approach is typically used for data...

Example MultiSided 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...

Simultaneous Assignment

There is an alternative form of the assignment statement that allows us to calculate several values all at the same time. It looks like this lt var gt , lt var gt , , lt var gt lt expr gt , lt expr gt , , lt expr gt This is called simultaneous assignment. Semantically, this tells Python to evaluate all the expressions on the right-hand side and then assign these values to the corresponding variables named on the left-hand side. Here's an example. Here sum would get the sum of x and y and diff...

Example The Projectile Class

Returning to the cannonball example, we want a class that can represent projectiles. This class will need a contructor to initialize instance variables, an update method to change the state of the projectile, and getX and getY methods so that we can find the current position. Let's start with the constructor. In the main program, we will create a cannonball from the initial angle, velocity and height. The Projectile class must have an __init__ method that uses these values to initialize the...

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...

Boolean Algebra

All decisions in computer programs boil down to appropriate Boolean expressions. The ability to formulate, manipulate and reason with these expressions is an important skill for programmers and computer scientists. Boolean expressions obey certain algebraic laws similar to those that apply to numeric operations. These laws are called Boolean logic or Boolean algebra. Let's look at a few examples. The following table shows some rules of algebra with their correlates in Boolean algebra. a 0 0 a...

Coming Attraction Objects

Have you noticed anything strange about the syntax of the file processing examples To apply an operation to a file, we use dot notation. For example, to read from infile we type infile.read . This is different from the normal function application that we have used before. Afterall, to take the absolute value of a variable x, we type abs x , not x.abs . In Python, a file is an example of an object. Objects combine both data and operations together. An object's operations, called methods, are...

Modularizing the Program

You may have noticed during the design discussion that I employed stepwise refinement top-down design to develop the program, but I did not divide the program into separate functions. We are going to modularize the program in two different ways. First, we'll use functions a la top-down design . While the final program is not too long, it is fairly complex for its length. One cause of the complexity is that it uses ten variables, and that is a lot for the reader to keep track of. Let's try...

Graphics Module Reference

The examples in this chapter have touched on most of the elements in the graphics module. This section provides a complete reference to the objects and functions provided in the graphics library. Experienced programmers use these sorts of guides to learn about new libraries. You will probably want to refer back to this section often when you are writing your own graphical programs. A GraphWin object represents a window on the screen where graphical images may be drawn. A program may define any...

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

1. 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...

Common Loop Patterns Interactive Loops

One good use of the indefinite loop is to write interactive loops. The idea behind an interactive loop is that it allows the user to repeat certain portions of a program on demand. Let's take a look at this loop pattern in the context of our number averaging problem. Recall that the previous version of the program forced the user to count up how many numbers there were to be averaged. We want to modify the program so that it keeps track of how many numbers there are. We can do this with another...

Exercises Kex

a few lines of code using Boolean operators this way. If Just make sure that your code doesn't get so tricky that 1. Compare and contrast the following pairs of terms. a Definite loop vs. Indefinite loop c Interactive loop vs. Sentinel loop d Sentinel loop vs. End-of-file loop 2. Give a truth table that shows the Boolean value of each of the following Boolean expressions, for every possible combination of input values. Hint including columns for intermediate expressions is helpful. 3. Write a...

Exercises Rpp

import string s1 2,1,4,3 s2 'c','a','b' show the result of evaluating each of the following sequence expressions 2. Given the same initial statements as in the previous problem, show the values of s1 and s2 after executing each of the following statements. Treat each part independently i.e., assume that s1 and s2 start with their original values each time . 3. Modify the statistics package from the chapter so that client programs have more flexibility in computing the mean and or standard...

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...

Exercises Dzw

1. 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...

Case Study Racquetball Simulation

For our first case study, let's return to the racquetball simulation from Chapter 9. You might want to go back and review the program that we developed the first time around using top-down design. The crux of the problem is to simulate multiple games of racquetball where the ability of the two opponents is represented by the probability that they win a point when they are serving. The inputs to the simulation are the probability for player A, the probability for player B, and the number of...

Sentinel Loops

A better solution to the number averaging problem is to employ a pattern commonly known as a sentinel loop. A sentinel loop continues to process data until reaching a special value that signals the end. The special value is called the sentinel. Any value may be chosen for the sentinel. The only restriction is that it be distinguishable from actual data values. The sentinel is not processed as part of the data. Here is a general pattern for designing sentinel loops get the first data item while...

Recursive Search

Now that we have a technique for implementing recursive definitions, we are ready to go back and look again at binary search as a recursive process. The basic idea was to look at the middle value and then recursively search either the lower half or the upper half of the array. The base cases for the recursion are the conditions when we can stop, namely when the target value is found, or we run out of places to look. The recursive calls will cut the size of the problem in half each time. In...

Exception Handling

Our quadratic program uses decision structures to avoid taking the square root of a negative number and generating a run-time error. This is a common pattern in many programs using decisions to protect against In the case of the quadratic solver, we checked the data before the call to the sqrt function. Sometimes functions themselves check for possible errors and return a special value to indicate that the operation was unsuccessful. For example, a different square root operation might return a...

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...

Study in Design Max of Three

Now that we have decisions that can alter the control flow of a program, our algorithms are liberated from the monotony of step-by-step, strictly sequential processing. This is both a blessing and a curse. The positive side is that we can now develop more sophisticated algorithms, as we did for our quadratic solver. The negative side is that designing these more sophisticated algorithms is much harder. In this section, we'll step through the design of a more difficult decision problem to...

PostTest 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...

Exercises Qmt

1. Pick an example of an interesting real-world object and describe it as a programming object by listing its data attributes, what it knows and its methods behaviors, what it can do . 2. Describe in your own words the object produced by each of the following operations from the graphics module. Be as precise as you can. Be sure to mention such things as the size, position, and appearance of the various objects. You may include a sketch if that helps. b c Circle Point 30,40 ,25 c.setFill 'blue'...

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...

A Certain Cs Professor Gives

1. 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...

Exercises Vbl

1. 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...