Graphing Future Value

Now that you have some idea of how to use objects from the graphics module, we're ready to try some real graphics programming. One of the most important uses of graphics is providing a visual representation of data. They say a picture is worth a thousand words it is almost certainly better than a thousand numbers. Few programs that manipulate numeric data couldn't be improved with a bit of graphical output. Remember the program in Chapter 2 that computed the future value of a ten year...

Inside a Python Program

The output from the chaos program may not look very exciting, but it illustrates a very interesting phenomenon known to physicists and mathematicians. Let's take a look at this program line by line and see what it does. Don't worry about understanding every detail right away we will be returning to all of these ideas in the next chapter. The first two lines of the program start with the character A simple program illustrating chaotic behavior. These lines are called comments. They are intended...

Statistics with Lists

Now that you know more about lists, we are ready to solve our little statistics problem. Recall that we are trying to develop a program that can compute the mean, median and standard deviation of a sequence of numbers entered by the user. One obvious way to approach this problem is to store the numbers in a list. We can write a series of functions mean, stdDev and median that take a list of numbers and calculate the corresponding statistics. Let's start by using lists to rewrite our original...

Using Graphical Objects

Some of the examples in the above interactions may look a bit strange to you. To really understand the graphics module, we need to take an object-oriented point of view. Recall, objects combine data with operations. Computation is performed by asking an object to carry out one of its operations. In order to make use of objects, you need to know how to create them and how to request operations. In the interactive examples above, we manipulated several different kinds of objects GraphWin, Point,...

Accumulating Results Factorial

Suppose you have a root beer sampler pack containing six different kinds of root beer. Drinking the various flavors in different orders might affect how good they taste. If you wanted to try out every possible ordering, how many different orders would there be It turns out the answer is a surprisingly large number, 720. Do you know where this number comes from The value 720 is the factorial of 6. In mathematics, factorial is often denoted with an exclamation ( ). The factorial of a whole number...

Graphics Programming

Modern computer applications are not limited to the sort of textual input and output that we have been using so far. Most of the applications that you are familiar with probably have a so-called Graphical User Interface (GUI) that provides visual elements like windows, icons (representative pictures), buttons and menus. Interactive graphics programming can be very complicated entire textbooks are devoted to the intricacies of graphics and graphical interfaces. Industrial-strength GUI...

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

Old Macdonald Program Using For Loopin Python

In your own words, describe the two motivations for defining functions in your programs. 2. We have been thinking about computer programs as sequences of instructions where the computer methodically executes one instruction and then moves on to the next one. Do programs that contain functions fit this model Explain your answer. 3. Parameters are an important concept in defining functions. (a) What is the purpose of parameters (b) What is the difference between a formal parameter and an actual...

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

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

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

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

Python Program On Miles Per Gallon Loop

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

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