Ebook The practice of computing using python (2nd edition) Part 1

283 538 0
Ebook The practice of computing using python (2nd edition) Part 1

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

(BQ) Part 1 book The practice of computing using python has contents: The study of computer science, beginnings, control, algorithms and program development, working with strings, files and exceptions I.

Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo Editorial Director, ECS: Marcia Horton Editor-in-Chief: Michael Hirsch Acquisitions Editor: Matt Goldstein Editorial Assistant: Chelsea Kharakozova Director of Marketing: Patrice Jones Marketing Manager: Yezan Alayan Marketing Coordinator: Kathryn Ferranti Director of Production: Vince O’Brien Managing Editor: Jeff Holcomb Manufacturing Buyer: Lisa McDowell Cover Designer: Anthony Gemmellaro Media Editor: Daniel Sandin Media Project Manager: John Cassar Full-Service Project Management: Peggy Kellar, Aptara® Corporation Composition: Aptara® Corporation Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on appropriate page within text Reprinted with permission Unless otherwise noted, Screenshot by Microsoft Copyright © 2011 by the Microsoft Corporation Reprinted with permission./Screenshot by Python Copyright © 2001–2010 by Python Software Foundation All Rights Reserved Reprinted with permission Cover Photo Credit: LanaN./Shutterstock.com, Stephen Aaron Rees/Shutterstock.com, Fotonic/Shutterstock.com, Robert Adrian Hillman/Shutterstock.com, dmiskv/Shutterstock.com, Dan Ionut Popescu/Shutterstock.com, AlexRoz/Shutterstock.com, Irin-K/Shutterstock.com, S.Borisov/Shutterstock.com, © UK History/Alamy The programs and applications presented in this book have been included for their instructional value They have been tested with care but are not guaranteed for any particular purpose The publisher does not offer any warranty or representation, nor does it accept any liabilities with respect to the programs or applications Copyright © 2013, 2011 Pearson Education, Inc., publishing as Addison-Wesley All rights reserved Printed in the United States of America This publication is protected by Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to 201-236-3290 Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps Library of Congress Cataloging-in-Publication Data available upon request 10 ISBN 10: 0-13-280557-X ISBN 13: 978-0-13-280557-5 To our long-suffering spouses, Laurie and Wendy; our kids, Zach, Alex, Abby, Carina, and Erik; and our parents We love you and couldn’t have done this without your love and support This page intentionally left blank • B R I E F C O N T E N T S PREFACE xxiii PART THINKING ABOUT COMPUTING Chapter The Study of Computer Science PART STARTING TO PROGRAM Chapter Chapter Chapter Chapter Chapter 35 Beginnings 37 Control 81 Algorithms and Program Development 153 Working with Strings 179 Files and Exceptions I 227 PART FUNCTIONS AND DATA STRUCTURES Chapter Chapter Chapter Chapter Chapter 10 255 Functions—QuickStart 257 Lists and Tuples 283 More on Functions 357 Dictionaries and Sets 383 More Program Development 437 PART CLASSES, MAKING YOUR OWN DATA STRUCTURES AND ALGORITHMS 475 Chapter 11 Introduction to Classes 477 Chapter 12 More on Classes 517 Chapter 13 Program Development with Classes 561 PART BEING A BETTER PROGRAMMER 589 Chapter 14 Files and Exceptions II 591 Chapter 15 Testing 631 v vi BRIEF CONTENTS Chapter 16 Recursion: Another Control Mechanism 649 Chapter 17 Other Fun Stuff with Python 667 Chapter 18 The End, or Perhaps the Beginning 695 APPENDICES 697 Appendix A Appendix B Appendix C Appendix D Appendix E Appendix F Appendix G INDEX 749 Getting and Using Python 697 Simple Drawing with Turtle Graphics 709 Plotting and Numeric Tools: A Quick Survey 721 Table of UTF-8 One-Byte Encodings 735 Precedence 737 Naming Conventions 739 Check Yourself Solutions 743 • C O N T E N T S PREFACE xxiii PART THINKING ABOUT COMPUTING Chapter The Study of Computer Science 0.1 Why Computer Science? 0.1.1 Importance of Computer Science 0.1.2 Computer Science Around You 0.1.3 Computer “Science” 0.1.4 Computer Science Through Computer Programming 0.2 The Difficulty and Promise of Programming 0.2.1 Difficulty 1: Two Things at Once 0.2.2 Difficulty 2: What Is a Good Program? 0.2.3 The Promise of a Computer Program 10 0.3 Choosing a Computer Language 11 0.3.1 Different Computer Languages 11 0.3.2 Why Python? 11 0.3.3 Is Python the Best Language? 13 0.4 What Is Computation? 0.5 What Is a Computer? 13 0.5.1 Computation in Nature 14 0.5.2 The Human Computer 17 0.6 The Modern, Electronic Computer 0.6.1 It’s the Switch! 18 0.6.2 The Transistor 19 0.7 A High-Level Look at a Modern Computer 24 0.8 Representing Data 26 0.8.1 Binary Data 26 0.8.2 Working with Binary 27 13 18 vii viii CONTENTS 0.8.3 0.8.4 0.8.5 0.8.6 0.8.7 0.8.8 0.9 Limits 28 Representing Letters 29 Representing Other Data 30 What Does a Number Represent? 31 How to Talk About Quantities of Data 32 Quantities of Data 32 Overview of Coming Chapters PART STARTING TO PROGRAM Chapter Beginnings 34 35 37 1.1 Practice, Practice, Practice 37 1.2 QuickStart, the Circumference Program 38 1.2.1 Examining the Code 40 1.3 An Interactive Session 1.4 Parts of a Program 43 1.4.1 Modules 43 1.4.2 Statements and Expressions 43 1.4.3 Whitespace 45 1.4.4 Comments 46 1.4.5 Special Python Elements: Tokens 46 1.4.6 Naming Objects 48 1.4.7 Recommendations on Naming 49 1.5 Variables 49 1.5.1 Variable Creation and Assignment 1.6 1.7 42 Objects and Types 53 1.6.1 Numbers 55 1.6.2 Other Built-in Types 57 1.6.3 Object Types: Not Variable Types 1.6.4 Constructing New Values 59 50 58 Operators 61 1.7.1 Integer Operators 61 1.7.2 Floating-Point Operators 63 1.7.3 Mixed Operations 63 1.7.4 Order of Operations and Parentheses 64 1.7.5 Augmented Assignment Operators: A Shortcut! 1.8 Your First Module, Math 67 1.9 Developing an Algorithm 68 1.9.1 New Rule, Testing 72 1.10 Visual Vignette: Turtle Graphics 73 65 CONTENTS Chapter Control 81 2.1 Chapter The Selection Statement for Decisions: if 81 2.1.1 Booleans for Decisions 83 2.1.2 The if Statement 83 2.1.3 Example: What Lead Is Safe in Basketball? 2.1.4 Repetition 90 2.1.5 Example: Finding Perfect Numbers 94 2.1.6 Example: Classifying Numbers 99 2.2 In-Depth Control 103 2.2.1 True and False: Booleans 103 2.2.2 Boolean Variables 104 2.2.3 Relational Operators 104 2.2.4 Boolean Operators 109 2.2.5 Precedence 110 2.2.6 Boolean Operators Example 111 2.2.7 Another Word on Assignments 114 2.2.8 The Selection Statement for Decisions 116 2.2.9 More on Python Decision Statements 116 2.2.10 Repetition: The while Statement 120 2.2.11 Sentinel Loop 130 2.2.12 Summary of Repetition 130 2.2.13 More on the for Statement 131 2.2.14 Nesting 134 2.2.15 Hailstone Sequence Example 136 2.3 Visual Vignette: Plotting Data with Pylab 137 2.3.1 First Plot and Using a List 138 2.3.2 More Interesting Plot: A Sine Wave 140 2.4 Computer Science Perspectives 142 2.4.1 Minimal Universal Computing 142 Algorithms and Program Development 153 3.1 What Is an Algorithm? 153 3.1.1 Example Algorithms 154 3.2 Algorithm Features 155 3.2.1 Algorithm Versus Program 155 3.2.2 Qualities of an Algorithm 157 3.2.3 Can We Really Do All That? 159 3.3 What Is a Program? 159 3.3.1 Readability 159 3.3.2 Robustness 163 3.3.3 Correctness 164 86 ix 240 CHAPTER • FILES AND EXCEPTIONS Straight Flush 6 Four of a Kind 9 10 Flush Straight Three of a Kind 9 10 One Pair 5 High Cards 10 10 10 10 6 7 10 10 10 10 9 9 Two Pair 10 7 10 9 10 10 10 9 10 9 Full House 10 10 I FIGURE 5.2 Poker hand rankings 5.7 • EXAMPLE: COUNTING POKER HANDS 241 C1-suit, C1-rank, C2-suit, C2-rank, C3-suit, C3-rank, C4-suit, C4-rank, C5-suit, C5-rank, hand rank TABLE 5.3 Poker File Format 3, 10, 1, 7, 2, 12, 4, , 2, 1, 4, 9, 4, 12, 4, 13, 2, , 3, 4, 3, 2, 2, 2, 3, 12, 3, , 4, 2, 4, 11, 2, 8, 1, 13, 4, , 1, 7, 4, 8, 3, 8, 1, 3, 1, , 3, 7, 2, 7, 2, 5, 3, 10, 4, 13 , 3, 7, 1, 4, 3, 4, 3, 5, 4, 10 , 2, 10, FIGURE 5.3 Poker file—seven lines out of million represents a hand with rank 3, which is “three of a kind”—there are three cards of rank in the hand: of diamonds, of spades, and of clubs The next three hands each have one pair (hand rank 1): 7s, 8s and then 7s again The final hand has two pairs (hand rank 2): 4s and 10s 5.7.1 Program to Count Poker Hands Now that we understand the file format, how will we count hands? First, observe that all we care about is the last column of the line of the file, which indicates that hand’s rank Someone has already determined hand rank for us (something you will be able to yourself by the end of the book) Remember that the 11th column is index number 10, as we start indexing at Program to Count the Total Hands in the File As always, a useful strategy is to develop a program a little at a time In this case, let’s begin with a program that counts the number of hands in the file We know that there should be million—let’s see if we get that Here is our algorithm: Open the file for reading Create a variable to hold our count and initialize it to Loop through the file, adding to our counter each time we get a line Print the value of the counter Let’s name the variable to hold our count total count int We create a file object poker file by using the open function, giving a file name as an argument As we have seen, the for iterates through all the lines of the file, and we add to total count int 242 CHAPTER • FILES AND EXCEPTIONS I for each line The program counts the number of lines in the file In the output, we see that we indeed have million hands See Code Listing 5.3 Code Listing 5.3 # count poker hands # open the poker data f i l e f o r reading poker file = open("poker-hand-testing.data",'r') total count int = # c r e a t e v a r i a b l e to hold the count −− i n i t i a l i z e d i t # s t e p through each l i n e o f the f i l e for line str in poker file: total count int = total count int + # at each l i n e increment the counter print("Total hands in file:", total count int) >>> Total hands in file: >>> 1000000 Program to Count the Hands with One Pair Now that we can loop through the file examining every line, let’s take another step toward our goal Using a for loop, we read each line of the file into the variable line str Using this line, let’s count the number of hands with exactly one pair Such a hand has a rank 1, so we need to examine the last (rightmost) item in each line to determine that hand’s rank Remember, each line represents a hand of poker The line is formatted in a common text format known as comma-separated value (CSV) format A CSV format separates multiple fields in a single line of data by commas, as you saw in Table 5.3 To access each individual field in a line, we can split the line on a comma character and then examine the last field The split method returns a data structure we have not yet discussed, a list (see Chapter 7), but for now all we need to know is that split separates the string into individual string elements For this example, the separation character is a comma (‘,’), so we get 11 different string fields for each line, and we store those fields in the fields variable Because a list indexes in the same way as a string, we can use an index of -1 to reference the last field Remember that split returns each individual field as type str, so we must convert any field element to an int if we wish to arithmetic on it We also 5.7 • EXAMPLE: COUNTING POKER HANDS 243 need a variable to hold our count of pairs, pair count int, and remember to initialize it to Let’s update our algorithm with these changes highlighted in italics Remember that at this point we are only counting pairs See Code Listing 5.4 Open the file for reading Create variables to hold our counts and initialize them to Loop through the file reading one line at a time, (a) add to our total counter each time we read a line (b) get the hand rank: split on comma and get the last item (index -1) (c) if handRank is 1, then add to our pair counter Print the values of the counter Code Listing 5.4 # count poker hands # open the poker data f i l e f o r reading poker file = open("poker-hand-testing.data",'r') total count int = # c r e a t e and i n i t i a l i z e v a r i a b l e to hold the t o t a l count pair count int = # c r e a t e and i n i t i a l i z e v a r i a b l e to hold pair count # Loop through each l i n e o f the f i l e for line str in poker file: total count int = total count int + # ( a ) add one t o t a l f o r each hand fields = line str.split(',') hand rank str = fields[-1] hand rank int = int(hand rank str) # (b) s p l i t on a comma # and g e t the l a s t f i e l d if hand rank int == 1: #( c ) i f handRank i s ( i t i s a pair ) pair count int = pair count int + # print("Total hands in file: ", total count int) print("Count of pair hands: ", pair count int) >>> Total hands in file: Count of pair hands: >>> 1000000 422498 add one to pair count # pr i n t the v a l u e s 244 CHAPTER • FILES AND EXCEPTIONS I The for loop assigns the next line from the file to the line str variable The line str is a string of 11 comma-separated fields We use the split function, line str.split(','), to split the line at the commas and store the 11 resulting strings in the fields variable, and then we grab the last item, fields[-1], which is the hand rank However, the resulting hand rank str is still a string, so we must convert it to an integer using int(hand rank str) We can now check to see whether the converted hand rank int has a value of 1—remember that checking equality in Python uses a double-equal sign (==) If its value is 1, that is, if hand rank int == 1:, that hand contains one pair, so we increment the pair count: pair count int = pair count int + Program to Calculate the Probability of One Pair An astute reader will have noticed that we wanted a probability but only did a count Calculating such a probability is straightforward: the count of pairs divided by the total number of hands in the file Simply including the expression pair count int/total count int provides the probability Python division yields the appropriate floating point, and we convert the result to a percentage using the “%” formatting command in the format statement Let us experiment with these calculations and printing the results in a session After running the program in the consle, the values for pair count int and total count int are still available, so we can play with them in the Python shell Here is a session showing how the Python shell can be used to develop expressions to put into the program We want nicely aligned output, so we use right justification, limit the number of decimal points, and automatically convert to percentages: >> ================================ RESTART =========================== >>> Total hands in file: 1000000 Count of pair hands: 422498 >>> pair count int/total count int 0.422498 >>> print("result:{}".format(pair count int/total count int)) result:0.422498 >>> print("result:{:%}".format(pair count int/total count int)) result:42.249800% >>> print("result:{:5.2%}".format(pair count int/total count int)) result:42.25% >>> print("result:{:>9.4%}".format(pair count int/total count int)) result: 42.2498% >>> 5.7 • EXAMPLE: COUNTING POKER HANDS 245 We can now put that expression into our code and try it out in Code Listing 5.5 Code Listing 5.5 # count poker hands # open the poker data f i l e f o r reading poker file = open("poker-hand-testing.data",'r') total count int = # c r e a t e and i n i t i a l i z e v a r i a b l e to hold the t o t a l count pair count int = # c r e a t e and i n i t i a l i z e v a r i a b l e to hold pair count # Loop through each l i n e o f the f i l e for line str in poker file: total count int = total count int + # ( a ) add one t o t a l f o r each hand fields = line str.split(',') hand rank str = fields[-1] hand rank int = int(hand rank str) # (b) s p l i t on a comma # and g e t the l a s t f i e l d if hand rank int == 1: #( c ) i f handRank i s ( i t i s a pair ) pair count int = pair count int + # add one to pair count print("Total hands in file: ", total count int) # pr i n t the v a l u e s print("Count of pair hands: ", pair count int) print("Probability of a pair: {:>9.4%}".format(pair count int/ total count int)) >>> Total hands in file: 1000000 Count of pair hands: 422498 Probability of a pair: 42.2498% >>> Error Checking Now that we have the basic code working, let’s add error checking—i.e., apply RULE Our initial code had a fixed file for input A more general approach would be to prompt for a file name and then ensure that it opened correctly before proceeding We can that by putting a try-except block into a while True infinite loop and then break out of the loop if the file is opened successfully A file that fails to open will raise an IOError exception, so 246 CHAPTER • FILES AND EXCEPTIONS I that is the exception name we catch Once we break out of the file opening loop we know that the file has opened and we can move on A second error check can be made where we read the hand type from the file There we convert the input to an int and we can check if that conversion was successful If it fails, we have chosen to ignore the line as bad input and not count it The revised code to count pairs is in Code Listing 5.6 Code Listing 5.6 # count poker hands # open the poker data f i l e f o r reading file str = input("Enter a file name: ") # loop u n t i l you break while True: try: poker file = open(file str,'r') # s u c c e s s ! s o move on to r e s t o f program break except IOError: print("Error opening file:",file str) file str = input("Enter a file name: ") total count int = # c r e a t e and i n i t i a l i z e v a r i a b l e to hold the t o t a l count pair count int = # c r e a t e and i n i t i a l i z e v a r i a b l e to hold pair count # Loop through each l i n e o f the f i l e for line str in poker file: total count int = total count int + # ( a ) add one t o t a l f o r each hand fields = line str.split(',') # (b) s p l i t on a comma hand rank str = fields[-1] # and g e t the l a s t f i e l d try: hand rank int = int(hand rank str) except ValueError: # bad l i n e : q u i e t l y s k i p t h i s l i n e o f the continue file if hand rank int == 1: #( c ) i f handRank i s ( i t i s a pair ) pair count int = pair count int + # add one to pair count print("Total hands in file: ", total count int) # pr i n t the v a l u e s print("Count of pair hands: ", pair count int) print("Probability of a pair: {:>9.4%}".format(pair count int/ total count int)) 5.7 • EXAMPLE: COUNTING POKER HANDS 247 The Rest of the Program We now have a partial program that calculates the probability of getting a poker hand with just one pair To complete the program, we must include a counter for each type of hand We need a counter for each type of hand, and we need to increment that counter each time that type of hand is encountered The resulting program is quite a bit longer, but if you examine it carefully, you will see that we simply duplicated the counter initialization and increment statements (Later, you will learn how to write a more compact program with one compound counter as a list to accommodate all 10 types of hands.) Also, some details need to be decided upon—a common issue in problem solving: the devil is in the details In this case, when we count the number of flush-type hands, we include straight flushes, or is the flush count really “flushes that are not straight flushes”? For simplicity, we have chosen the latter, but either would be reasonable Finally, a note on naming Remember RULE 4: we can modify rules if it helps in readability Every count in the program is an integer, and it seems, at least for this program, that “count” and “int” are redundant So we modify our names to make them a bit more compact but add a comment to notify the reader that every count variable is an int The final code is shown in Code Listing 5.7 Code Listing 5.7 # count poker hands # open the poker data f i l e f o r reading file str = input("Enter a file name: ") # loop u n t i l you break while True: try: poker file = open(file str,'r') # s u c c e s s ! s o move on to r e s t o f program break except IOError: print("Error opening file:",file str) file str = input("Enter a file name: ") # a l l counts are i n t s , s o count as a s u f f i x i s enough total count = = nothing count = pair count = two pair count three of a kind count= = straight count = flush count = full house count four of a kind count = 0 0 0 0 248 CHAPTER • FILES AND EXCEPTIONS I straight flush count = = royal flush count for line str in poker file: total count = total count + # s p l i t on a comma fields = line str.split(',') hand rank str = fields[-1] # and g e t the l a s t f i e l d try: hand rank int = int(hand rank str) except ValueError: # bad l i n e : q u i e t l y s k i p t h i s l i n e o f the f i l e continue if hand rank int == 1: pair count = pair count + elif hand rank int == 2: two pair count = two pair count + elif hand rank int == 3: three of a kind count = three of a kind count + elif hand rank int == 4: straight count = straight count + elif hand rank int == 5: flush count = flush count + elif hand rank int == 6: full house count = full house count + elif hand rank int == 7: four of a kind count = four of a kind count + elif hand rank int == 8: straight flush count = straight flush count + elif hand rank int == 9: royal flush count = royal flush count + else: nothing count = nothing count + print("Total hands in file: ", total count) print("Hand counts by rank number: ", nothing count, pair count, two pair count, \ three of a kind count, straight count, flush count, full house count, \ four of a kind count, straight flush count, royal flush count ) print("Probability:") print(" of nothing: total count)) print(" of one pair: total count)) print(" of two pairs: total count)) {:>9.4%} ".format( nothing count/ {:>9.4%} ".format( pair count/ {:>9.4%} ".format( two pair count/ 5.7 • EXAMPLE: print(" of three of a kind: {:>9.4%} total count)) {:>9.4%} print(" of a straight: total count)) {:>9.4%} print(" of a flush: total count)) {:>9.4%} print(" of a full house: total count)) print(" of four of a kind: {:>9.4%} total count)) print(" of a straight flush:{:>9.4%} total count)) {:>9.4%} print(" of a royal flush: total count)) COUNTING POKER HANDS 249 ".format(three of a kind count/ ".format( straight count/ ".format( flush count/ ".format( full house count/ ".format( four of a kind count/ ".format( straight flush count/ ".format( royal flush count/ Enter a file name: poker-hand-testing.data Total hands in file: 1000000 Hand counts by rank number: 501209 422498 47622 21121 3885 1996 1424 230 12 Probability: of nothing: 50.1209% of one pair: 42.2498% of two pairs: 4.7622% of three of a kind: 2.1121% of a straight: 0.3885% of a flush: 0.1996% of a full house: 0.1424% of four of a kind: 0.0230% of a straight flush: 0.0012% of a royal flush: 0.0003% Notice how spacing was used to make both the program and the output more readable Also, in the statement that prints the counts, notice a backslash (\) Remember, the backslash indicates that the statement continues onto the next line—usually a newline or carriage return indicates the end of a statement This improves the readability of the code, which is important, but it does not affect running the code Observations on the Output The final output is interesting Notice that slightly more than half the possible hands have no value, and that a hand with only one pair makes up almost all the remaining possibilities 250 CHAPTER • FILES AND EXCEPTIONS I Summary In this chapter we introduced file reading and writing, with more detail to come in a later chapter We also introduced exceptions as a way to handle errors again with more details to come in a later chapter Files r Text files contain Unicode characters All other files are called binary files r Files need to be opened for reading: file handle = open("file name","r") for line str in file handle: r Files need to be opened for writing: file handle = open("file name","w") print(string,file=file handle) r When done, files are closed using file handle.close() Exceptions r Exceptions handle exceptional events such as errors r Errors raise exceptions with particular names Two of the most common are: - ValueError: errors when converting strings to numbers - IOError: errors when opening files r Exception syntax: try: # suite except ErrorName: # suite Rules r RULE 1: Think before you program! r RULE 2: A program is a human-readable essay on problem solving that also happens to execute on a computer r RULE 3: The best way to improve your programming and problem skills is to practice! r RULE 4: A foolish consistency is the hobgoblin of little minds r RULE 5: Test your code, often and thoroughly! EXERCISES 251 r RULE 6: If it was hard to write, it is probably hard to read Add a comment r RULE 7: All input is evil, until proven otherwise Exercises Why is closing a file important? Be specific In the exception example of Section 5.6.4, when error “(2) bad file name” occurred the user had to enter a line number before the error occurred Rewrite the code so that if a bad file name is entered, the error will be handled before a line number is requested In the exception example of Section 5.6.4, rewrite the code so that if error “(2) bad file name” occurs the program keeps asking for input until the user gets it right In the exception example of Section 5.6.4, rewrite the code so that if error “(3) bad line number (string)” occurs the program keeps asking for input until the user gets it right In the exception example of Section 5.6.4, rewrite the code so that if error “(4) line number not in file” occurs the program keeps asking for input until the user gets it right File manipulations: (a) Write a Python program that will open a file named thisFile.txt and write every other line into the file thatFile.txt (b) Extend your program using the os module to save your file to a different directory (folder) Create a file words.txt that contains a paragraph of random words (approximately 100 words long) Next, create a program that prompts for the file name then iterates through each word in this file and counts the frequency of each letter (a through z) and stores the values in a dictionary Make each letter lowercased and ignore punctuation Print a histogram of the word counts Create a test file with a single sentence of 20 words Read the file, then insert carriage-return characters (\n) and write the test to a new text file that will be composed of four lines of five words In the exercises for Chapters and 2, the football quarterback pass rating was developed into a program Go to http://nfl.com, find the quarterback data, and copy those data into a file It is easiest to grab the data of the “qualified” quarterbacks, as they fit on only one web page Write a program that reads your file, uses your pass rating function to calculate the pass ratings of the quarterbacks, and prints the players from best to worst 252 CHAPTER • FILES AND EXCEPTIONS I 10 Write a program that prompts for three numbers Divide the first number by the second number and add that result to the third number Using exceptions check for the following errors: ValueError, and ZeroDivisionError 11 Write a function named safe input(prompt,type) that works like the Python input function, except that it only accepts the specified type of input The function takes two arguments: r prompt: str r type: int, float, str The function will keep prompting for input until correct input of the specified type is entered The function returns the input If the input was specified to be a number (float or int), the value returned will be of the correct type; that is, the function will perform the conversion The default for a prompt is the empty string The default for the type is string 12 Write a function named prompt open that prompts for a file name and repeatedly attempts to read the specified file until a correctly specified file has been entered The function takes one mode argument, 'r' or 'w', and returns the file handle that open returns Programming Projects Scrambled Words Read the following paragraph as quickly as you can, and see if you encounter any difficulties Aoccdrnig to rscheearch at an Elingsh uinervtisy, it deosn’t mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht the frist and lsat ltteer is at the rghit pclae The rset can be a toatl mses and you can sitll raed it wouthit a porbelm Tihs is bcuseae we not raed ervey lteter by itslef but the wrod as a wlohe This has been presented as an example of a principle of human reading comprehension If you keep the first letter and the last letter of a word in their correct positions, then scramble the letters in between, the word is still quite readable in the context of an accompanying paragraph However, it seems that this is a bit of a myth and not truly based on solid research.5 In short, for longer words the task is much more difficult Nonetheless, we are going to imitate the process on some English text http://www.balancedreading.com/cambridge.html PROGRAMMING PROJECTS 253 The task will be to read in a paragraph from a file, scramble the internal letters of each word, and then write the result to a file Handling punctuation is tricky You are required to deal with punctuation that comes at the end of a word (period, question mark, exclamation, etc.)—that is, punctuation is left untouched and does not count as the final unscrambled letter Optionally, one can deal with the more difficult task of handling all punctuation, such as apostrophes for possessives or hyphenated words Truly randomizing the order of letters is a task for later in the text, but we can some reasonable approximations now Attacking this problem in a divide-and-conquer way should begin by writing code to scramble the letters in a word Here are three different approaches you might take, in increasing order of difficulty: (a) Easiest: Rotate letters by 13 (known as ROT13) That is, ‘a’ becomes ‘n’, ‘b’ becomes ‘o’, , ‘n’ becomes ‘a’, The chr and its inverse, ord, functions will be useful (b) Harder: For each letter choose a random number and rotate that letter by the random amount Import random and use the random.randint(a,b) function where ‘a’ and ‘b’ define the range of random numbers returned (c) Hardest: Improve on the above techniques by scrambling the letters by a method of your choice This page intentionally left blank ... Distance 5 01 11. 6.3 Summing Two Points 5 01 11. 6.4 Improving the Point Class 502 11 .7 Python and OOP 506 11 .7 .1 Encapsulation 506 11 .7.2 Inheritance 506 11 .7.3 Polymorphism 507 11 .8 An Aside: Python. .. 6 31 15 .1 Why Testing? 6 31 15 .1. 1 Kinds of Errors 6 31 15 .1. 2 “Bugs” and Debugging 632 15 .2 Kinds of Testing 633 15 .2 .1 Testing Is Hard! 634 15 .2.2 Importance of Testing 635 xvii xviii CONTENTS 15 .3... Working with Strings 17 9 4 .1 The String Type 18 0 4 .1. 1 The Triple-Quote String 18 0 4 .1. 2 Non-Printing Characters 18 1 4 .1. 3 String Representation 18 1 4 .1. 4 Strings as a Sequence 18 2 4 .1. 5 More Indexing

Ngày đăng: 16/05/2017, 09:31

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan