Dictionaries and tuples

Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value gt gt gt d 'a' 0, 'b' 1, 'c' 2 gt gt gt t d.items gt gt gt print t As you should expect from a dictionary, the items are in no particular order. Conversely, you can use a list of tuples to initialize a new dictionary gt gt gt t 'a', 0 , 'c', 2 , 'b', 1 gt gt gt d dict t gt gt gt print d 2This behavior is slightly different in Python 3.0. Combining dict with zip yields a concise way to create a...

Printing objects

In Chapter 16, we defined a class named Time and in Exercise 16.1, you wrote a function named represents the time of day. attributes hour, minute, second print ' .2d .2d .2d' time.hour, time.minute, time.second To call this function, you have to pass a Time object as an argument gt gt gt start Time gt gt gt start.hour 9 gt gt gt start.minute 45 gt gt gt start.second 00 gt gt gt print_time start 09 45 00 To make print_time a method, all we have to do is move the function definition inside the...

Exercises Brv

Exercise 9.7 This question is based on a Puzzler that was broadcast on the radio program Car Talk2 Give me a word with three consecutive double letters. I'll give you a couple of words that almost qualify, but don't. For example, the word committee, c-o-m-m-i-t-t-e-e. It would be great except for the 'i' that sneaks in there. Or Mississippi M-i-s-s-i-s-s-i-p-p-i. If you could take out those i's it would work. But there is a word that has three consecutive pairs of letters and to the best of my...

Time

As another example of a user-defined type, we'll define a class called Time that records the time of day. The class definition looks like this represents the time of day. attributes hour, minute, second We can create a new Time object and assign attributes for hours, minutes, and seconds time Time time.hour 11 time.minute 59 time.second 30 The state diagram for the Time object looks Exercise 16.1 Write a function called print_time that takes a Time object and prints it in the form hour minute...

Formal and natural languages

Natural languages are the languages people speak, such as English, Spanish, and French. They were not designed by people although people try to impose some order on them they evolved naturally. Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of...

The init method

The init method short for initialization is a special method that gets invoked when an object is instantiated. Its full name is_init_ two underscore characters, followed by init, and then two more underscores . An init method for the Time class might look like this def _init_ self, hour 0, minute 0, second 0 self.hour hour self.minute minute self.second second It is common for the parameters of_init_to have the same names as the attributes. The statement stores the value of the parameter hour...

Exercises Ayj

Exercise 16.6 Write a function called mul_time that takes a Time object and a number and returns a new Time object that contains the product of the original Time and the number. Then use mul_time to write a function that takes a Time object that represents the finishing time in a race, and a number that represents the distance, and returns a Time object that represents the average pace time per mile . Exercise 16.7 Write a class definition for a Date object that has attributes day, month and...

The Python programming language

The programming language you will learn is Python. Python is an example of a high-level language other high-level languages you might have heard of are C, C , Perl, and Java. There are also low-level languages, sometimes referred to as machine languages or assembly languages. Loosely speaking, computers can only execute programs written in low-level languages. So programs written in a high-level language have to be processed before they can run. This extra processing takes some time, which is a...

Debugging Kcp

When you use indices to traverse the values in a sequence, it is tricky to get the beginning and end of the traversal right. Here is a function that is supposed to compare two words and return True if one of the words is the reverse of the other, but it contains two errors if len wordl len word2 return False The first if statement checks whether the words are the same length. If not, we can return False immediately and then, for the rest of the function, we can assume that the words are the...

A development plan

A development plan is a process for writing programs. The process we used in this case study is encapsulation and generalization. The steps of this process are 1. Start by writing a small program with no function definitions. 2. Once you get the program working, encapsulate it in a function and give it a name. 3. Generalize the function by adding appropriate parameters. 4. Repeat steps 1-3 until you have a set of working functions. Copy and paste working code to avoid retyping and re-debugging...

Exercises Jdw

Exercise 19.4 For this exercise, you will write an image viewer. Here is a simple example canvas g.ca width 300 photo PhotoImage file 'danger.gif' canvas.image 0,0 , image photo g.mainloop PhotoImage reads a file and returns a PhotoImage object that Tkinter can display. Canvas. image puts the image on the canvas, centered on the given coordinates. You can also put images on labels, buttons, and some other widgets PhotoImage can only handle a few image formats, like GIF and PPM, but we can use...

Incremental development

As you write larger functions, you might find yourself spending more time debugging. To deal with increasingly complex programs, you might want to try a process called incremental development. The goal of incremental development is to avoid long debugging sessions by adding and testing only a small amount of code at a time. As an example, suppose you want to find the distance between two points, given by the coordinates x1 y1 and x2,y2 . By the Pythagorean theorem, the distance is distance J xi...

Debugging Neg

As you start writing bigger programs, you might find yourself spending more time debugging. More code means more chances to make an error and more place for bugs to hide. One way to cut your debugging time is debugging by bisection. For example, if there are 100 lines in your program and you check them one at a time, it would take 100 steps. Instead, try to break the problem in half. Look at the middle of the program, or near it, for an intermediate value you can check. Add a print statement or...

Glossary Jdx

modulus operator An operator, denoted with a percent sign , that works on integers and yields the remainder when one number is divided by another. boolean expression An expression whose value is either True or False. 2In Python 3.0, you no longer get an error message the division operator performs floating-point division even with integer operands. comparison operator One of the operators that compares its operands , , gt , lt , gt , and lt . logical operator One of the operators that combines...

Random words

To choose a random word from the histogram, the simplest algorithm is to build a list with multiple copies of each word, according to the observed frequency, and then choose from the list for word, freq in h.items t.extend word freq The expression word freq creates a list with freq copies of the string word. The extend method is similar to append except that the argument is a sequence. Exercise 13.7 This algorithm works, but it is not very efficient each time you choose a random word, it...

Comparing cards

For built-in types, there are conditional operators lt , gt , , etc. that compare values and determine when one is greater than, less than, or equal to another. For user-defined types, we can override the behavior of the built-in operators by providing a method named __cmp__ . _cmp_takes two parameters, self and other, and returns a positive number if the first object is greater, a negative number if the second object is greater, and 0 if they are equal to each other. The correct ordering for...

Write A Function Called Draw Point That Takes A Canvas And A Point As Arguments

Exercise 15.4 World. py, which is part of Swampy see Chapter 4 , contains a class definition for a user-defined type called World. You can import it like this This version of the import statement imports the World class from the World module. The following code creates a World object and calls the mainloop method, which waits for the user. A window should appear with a title bar and an empty square. We will use this window to draw Points, Rectangles and other shapes. Add the following lines...

Search

All of the exercises in the previous section have something in common they can be solved with the search pattern we saw in Section 8.6. The simplest example is for letter in word if letter 'e' return False return True The for loop traverses the characters in word. If we find the letter e, we can immediately return False otherwise we have to go to the next letter. If we exit the loop normally, that means we didn't find an e, so we return True. You can write this function more concisely using the...

Exercises Noh

Exercise 13.9 The rank of a word is its position in a list of words sorted by frequency the most common word has rank 1, the second most common has rank 2, etc. Zipf's law describes a relationship between the ranks and frequencies of words in natural languages2. Specifically, it predicts that the frequency, f, of the word with rank r is where s and c are parameters that depend on the language and the text. If you take the logarithm of both sides of this equation, you get So if you plot log f...

Markov analysis

If you choose words from the book at random, you can get a sense of the vocabulary, you probably won't get a sentence this the small regard harriet which knightley's it most things A series of random words seldom makes sense because there is no relationship between successive words. For example, in a real sentence you would expect an article like the to be followed by an adjective or a noun, and probably not a verb or adverb. One way to measure these kinds of relationships is Markov analysis1,...

Chained conditionals

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional print 'x is less than y' elif x gt y elif is an abbreviation of else if. Again, exactly one branch will be executed. There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn't have to be one. draw_b elif choice 'c' draw_c Each condition is checked in order. If the first is false,...

Exercise 12.3 Write A Function Called Most Frequent That Takes A String And

Exercise 12.3 Write a function called most_frequent that takes a string and prints the letters in decreasing order of frequency. Find text samples from several different languages and see how letter frequency varies between languages. Compare your results with the tables at wikipedia.org wiki Letter_frequencies. 1. Write a program that reads a word list from a file see Section 9.1 and prints all the sets of words that are anagrams. Here is an example of what the output might look like 'deltas',...

Exercises Rsy

Exercise 11.8 If you did Exercise 10.5, you already have a function named has_duplicates that takes a list as a parameter and returns T rue if there is any object that appears more than once in the list. Use a dictionary to write a faster, simpler version of has_duplicates. Exercise 11.9 Two words are rotate pairs if you can rotate one of them and get the other see rotate_word in Exercise 8.12 . Write a program that reads a wordlist and finds all the rotate pairs. Exercise 11.10 Here's another...

Stack diagrams for recursive functions

In Section 3.10, we used a stack diagram to represent the state of a program during a function call. The same kind of diagram can help interpret a recursive function. Every time a function gets called, Python creates anew function frame, which contains the function's local variables and parameters. For a recursive function, there might be more than one frame on the stack at the same time. As usual, the top of the stack is the frame for_main_. It is empty because we did not create any variables...

Variablelength argument tuples

Functions can take a variable number of arguments. A parameter name that begins with gathers arguments into a tuple. For example, printall takes any number of arguments and prints them The gather parameter can have any name you like, but args is conventional. Here's how the function works gt gt gt printall 1, 2.0, '3' 1, 2.0, '3' You can combine the gather operator with required and positional arguments def pointless required, optional 0, args print required, optional, args Run this function...

Exercises Qbo

Exercise 14.5 The urllib module provides methods for manipulating URLs and downloading information from the web. The following example downloads and prints a secret message from conn for line in conn.fp print line.strip Run this code and follow the instructions you see there. Exercise 14.6 In a large collection of MP3 files, there may be more than one copy of the same song, stored in different directories or with different file names. The goal of this exercise is to search for these duplicates....

Exercises Ehu

Exercise 3.3 Python provides a built-in function called len that returns the length of a string, so the value of len ' allen ' is 5. Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display. Exercise 3.4 A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an...

Dictionary subtraction

Finding the words from the book that are not in the word list from words .txt is a problem you might recognize as set subtraction that is, we want to find all the words from one set the words in the book that are not in another set the words in the list . subtract takes dictionaries d1 and d2 and returns a new dictionary that contains all the keys from d1 that are not in d2. Since we don't really care about the values, we set them all to None. def subtract d1, d2 res dict for key in d1 if key...

Random numbers

Given the same inputs, most computer programs generate the same outputs every time, so they are said to be deterministic. Determinism is usually a good thing, since we expect the same calculation to yield the same result. For some applications, though, we want the computer to be unpredictable. Games are an obvious example, but there are more. Making a program truly nondeterministic turns out to be not so easy, but there are ways to make it at least seem nondeterministic. One of them is to use...

TurtleWorld

To accompany this book, I have written a suite of modules called Swampy. One of these modules is TurtleWorld, which provides a set of functions for drawing lines by steering turtles around the screen. You can download Swampy from thinkpython. com swampy follow the instructions there to install Swampy on your system. Move into the directory that contains TurtleWorld.py, create a file named polygon.py and type in the following code world TurtleWorld bob Turtle print bob The first line is a...

Inheritance 1

The language feature most often associated with object-oriented programming is inheritance. Inheritance is the ability to define a new class that is a modified version of an existing class. It is called inheritance because the new class inherits the methods of the existing class. Extending this metaphor, the existing class is called the parent and the new class is called the child. As an example, let's say we want a class to represent a hand, that is, the set of cards held by one player. A hand...

Write A Function Called Is Sorted That Takes A List As A Parameter And Returns

Exercise 10.3 Write a function called is_sorted that takes a list as a parameter and returns True if the list is sorted in ascending order and False otherwise. You can assume as a precondition that the elements of the list can be compared with the comparison operators lt , gt , etc. For example, is_sorted 1,2,2 should return True and is_sorted 'b', 'a' should return False. Exercise 10.4 Two words are anagrams if you can rearrange the letters from one to spell the other. Write a function called...

Write A Function Named Avoids That Takes A Word And A String Of Forbidden

There are solutions to these exercises in the next section. You should at least attempt each one before you read the solutions. Exercise 9.2 In 1939 Ernest Vincent Wright published a 50,000 word novel called Gadsby that does not contain the letter e. Since e is the most common letter in English, that's not easy to do. In fact, it is difficult to construct a solitary thought without using that most common symbol. It is slow going at first, but with caution and hours of training you can gradually...

Def Draw T Length N

Exercise 5.1 Fermat's Last Theorem says that there are no integers a, b, and c such that 1. Write a function named check_fermat that takes four parameters a, b, c and n and that checks to see if Fermat's theorem holds. If n is greater than 2 and it turns out to be true that the program should print, Holy smokes, Fermat was wrong Otherwise the program should print, No, that doesn't work. 2. Write a function that prompts the user to input values for a, b, c and n, converts them to integers, and...

Exercises Wen

Exercise 8.9 A string slice can take a third index that specifies the step size that is, the number of spaces between successive characters. A step size of 2 means every other character 3 means every third, etc. gt gt gt fruit 'banana' gt gt gt fruit 0 5 2 ' bnn' A step size of -1 goes through the word backwards, so the slice -1 generates a reversed string. Use this idiom to write a one-line version of is_palindrome from Exercise 6.6. Exercise 8.10 Read the documentation of the string methods...

Write A Function Called Eval Loop That Iteratively Prompts The User Takes The

Exercise 7.3 To test the square root algorithm in this chapter, you could compare it with mat h.sqrt. Write a function named test_square_root that prints a table like this 41421356237 2 73205080757 0 00 2360679775 0 44948974278 0 64575131106 0 82842712475 4 00 The first column is a number, a the second column is the square root of a computed with the function from Exercise 7.2 the third column is the square root computed by math.sqrt the fourth column is the absolute value of the difference...

Long integers

If you compute fibonacci 50 , you get gt gt gt fibonacci 50 12586269025L The L at the end indicates that the result is a long integer2, or type long. Values with type int have a limited range long integers can be arbitrarily big, but as they get bigger they consume more space and time. The mathematical operators work on long integers, and the functions in the math module, too, so in general any code that works with int will also work with long. Any time the result of a computation is too big to...

Modulus operator

The modulus operator works on integers and yields the remainder when the first operand is divided by the second. In Python, the modulus operator is a percent sign . The syntax is the same as for other operators gt gt gt quotient 7 3 gt gt gt print quotient 2 gt gt gt remainder 7 3 gt gt gt print remainder 1 So 7 divided by 3 is 2 with 1 left over. The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another if x y is zero, then...

You Can Download A Solution From Thinkpython.com Code Letters.py

Exercise 17.6 This exercise is a cautionary tale about one of the most common, and difficult to find, errors in Python. 1. Write a definition for a class named Kangaroo with the following methods a An_init_method that initializes an attribute named pouch_contents to an empty b A method named put_in_pouch that takes an object of any type and adds it to c A_str_method that returns a string representation of the Kangaroo object and the Test your code by creating two Kangaroo objects, assigning...

Exercise 6.4 Draw A Stack Diagram For The Following Program

Exercise 6.4 Draw a stack diagram for the following program. What does the program print prod a z, z print z, prod return prod def a x, y x x 1 return x y sum x y z pow b sum 2 return pow Exercise 6.5 The Ackermann function, A m,n , is defined3 Write a function named ack that evaluates Ackerman's function. Use your function to evaluate ack 3, 4 , which should be 125. What happens for larger values of m and n Exercise 6.6 A palindrome is a word that is spelled the same backward and forward, like...

Class diagrams

So far we have seen stack diagrams, which show the state of a program, and object diagrams, which show the attributes of an object and their values. These diagrams represent a snapshot in the execution of a program, so they change as the program runs. They are also highly detailed for some purposes, too detailed. A class diagrams is a more abstract representation of the structure of a program. Instead of showing individual objects, it shows classes and the relationships between them. There are...

Exercises Pfy

Flowers Draw

Exercise 4.1 Download the code in this chapter from thinkpython.com code polygon.py. 1. Write appropriate docstrings for polygon, arc and circle. 2. Draw a stack diagram that shows the state of the program while executing circle bob, radius . You can do the arithmetic by hand or add print statements to the code. 3. The version of arc in Section 4.7 is not very accurate because the linear approximation of the circle is always outside the true circle. As a result, the turtle ends up a few units...

Word frequency analysis

As usual, you should at least attempt the following exercises before you read my solutions. Exercise 13.1 Write a program that reads a file, breaks each line into words, strips whitespace and punctuation from the words, and converts them to lowercase. Hint The string module provides strings named whitespace, which contains space, tab, newline, etc., and punctuation which contains the punctuation characters. Let's see if we can make Python swear gt gt gt import string gt gt gt print...

Exercises Abm

Exercise 18.5 The following are the possible hands in poker, in increasing order of value and decreasing order of probability two pair two pairs of cards with the same rank three of a kind three cards with the same rank straight five cards with ranks in sequence aces can be high or low, so Ace-2-3-4-5 is a straight and so is 10-Jack-Queen-King-Ace, but Queen-King-Ace-2-3 is not. flush five cards with the same suit full house three cards with one rank, two cards with another four of a kind four...

Prototyping versus planning

The development plan I am demonstrating is called prototype and patch. For each function, I wrote a prototype that performed the basic calculation and then tested it, patching errors along the way. This approach can be effective, especially if you don't yet have a deep understanding of the problem. But incremental corrections can generate code that is unnecessarily complicated since it deals with many special cases and unreliable since it is hard to know if you have found all the errors. An...

Reading word lists

For the exercises in this chapter we need a list of English words. There are lots of word lists available on the Web, but the one most suitable for our purpose is one of the word lists collected and contributed to the public domain by Grady Ward as part of the Moby lexicon project1. It is a list of 113,809 official crosswords that is, words that are considered valid in crossword puzzles and other word games. In the Moby collection, the filename is 113809of.fic I include a copy of this file,...

Dictionaries and lists

Lists can appear as values in a dictionary. For example, if you were given a dictionary that maps from letters to frequencies, you might want to invert it that is, create a dictionary that maps from frequencies to letters. Since there might be several letters with the same frequency, each value in the inverted dictionary should be a list of letters. Here is a function that inverts a dictionary def invert_dict d inv dict for key in d val d key if val not in inv inv val key Each time through the...