ebook img

Algorithmic Problem Solving with Python - The School of Electrical PDF

360 Pages·2015·1.96 MB·English
by  
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Algorithmic Problem Solving with Python - The School of Electrical

Algorithmic Problem Solving with Python John B. Schneider Shira Lynn Broschat Jess Dahmen May 31, 2015 ii Contents 1 Introduction 1 1.1 ModernComputers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 ComputerLanguages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.4 AlgorithmicProblemSolving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.5 ObtainingPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.6 RunningPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.6.1 InteractiveSessionsandComments . . . . . . . . . . . . . . . . . . . . . 9 1.6.2 RunningCommandsfromaFile . . . . . . . . . . . . . . . . . . . . . . . 11 1.7 Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.8 Thehelp()Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.9 CommentsonLearningNewLanguages . . . . . . . . . . . . . . . . . . . . . . . 14 1.10 ChapterSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.11 ReviewQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2 CoreBasics 19 2.1 LiteralsandTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2.2 Expressions,ArithmeticOperators,andPrecedence . . . . . . . . . . . . . . . . . 22 2.3 StatementsandtheAssignmentOperator . . . . . . . . . . . . . . . . . . . . . . 24 2.4 CascadedandSimultaneousAssignment . . . . . . . . . . . . . . . . . . . . . . 27 2.5 Multi-LineStatementsandMulti-LineStrings . . . . . . . . . . . . . . . . . . . . 29 2.6 IdentifiersandKeywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 2.7 NamesandNamespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 2.8 AdditionalArithmeticOperators . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 2.8.1 Exponentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 2.8.2 FloorDivision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 2.8.3 Moduloanddivmod() . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 2.8.4 AugmentedAssignment . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 2.9 ChapterSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 2.10 ReviewQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 2.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 3 InputandTypeConversion 51 3.1 ObtainingInput: input() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 3.2 ExplicitTypeConversion: int(),float(),andstr() . . . . . . . . . . . . . 53 iii iv CONTENTS 3.3 EvaluatingStrings: eval() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 3.4 ChapterSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 3.5 ReviewQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 3.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 4 Functions 67 4.1 VoidFunctionsandNone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 4.2 CreatingVoidFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 4.3 Non-VoidFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 4.4 ScopeofVariables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 4.5 ScopeofFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 4.6 print()vs.return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 4.7 Usingamain()Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 4.8 OptionalParameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 4.9 ChapterSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 4.10 ReviewQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 4.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 5 IntroductiontoObjects 95 5.1 OverviewofObjectsandClasses . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 5.2 CreatingaClass: Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 5.3 CreatingaClass: Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 5.4 Thedir()Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 5.5 The init ()Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 5.6 OperatorOverloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 5.7 Take-AwayMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 5.8 ChapterSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 6 Listsandfor-Loops 109 6.1 lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 6.2 listMethods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 6.3 for-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 6.4 Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 6.5 range() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 6.6 Mutability,Immutability,andTuples . . . . . . . . . . . . . . . . . . . . . . . . . 121 6.7 NestingLoopsinFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 6.8 SimultaneousAssignmentwithLists . . . . . . . . . . . . . . . . . . . . . . . . . 126 6.9 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 6.9.1 StoringEntriesinalist . . . . . . . . . . . . . . . . . . . . . . . . . . 127 6.9.2 Accumulators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 6.9.3 FibonacciSequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 6.10 ChapterSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 6.11 ReviewQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 CONTENTS v 7 Moreonfor-Loops,Lists,andIterables 143 7.1 for-Loopswithinfor-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 7.2 listsoflists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 7.2.1 IndexingEmbeddedlists . . . . . . . . . . . . . . . . . . . . . . . . . 151 7.2.2 SimultaneousAssignmentandlistsoflists . . . . . . . . . . . . . . 154 7.3 ReferencesandlistMutability . . . . . . . . . . . . . . . . . . . . . . . . . . 157 7.4 StringsasIterablesorSequences . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 7.5 NegativeIndices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 7.6 Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 7.7 listComprehension(optional) . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 7.8 ChapterSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 7.9 ReviewQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 8 ModulesandimportStatements 177 8.1 ImportingEntireModules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 8.2 IntroductiontoComplexNumbers . . . . . . . . . . . . . . . . . . . . . . . . . . 181 8.3 ComplexNumbersandthecmathModule . . . . . . . . . . . . . . . . . . . . . 185 8.4 ImportingSelectedPartsofaModule . . . . . . . . . . . . . . . . . . . . . . . . 187 8.5 ImportinganEntireModuleUsing* . . . . . . . . . . . . . . . . . . . . . . . . . 189 8.6 ImportingYourOwnModule . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 8.7 ChapterSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 8.8 ReviewQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 9 Strings 195 9.1 StringBasics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 9.2 TheASCIICharacters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 9.3 EscapeSequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 9.4 chr()andord() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 9.5 AssortedStringMethods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 9.5.1 lower(),upper(),capitalize(),title(),andswapcase() . 209 9.5.2 count() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 9.5.3 strip(),lstrip(),andrstrip() . . . . . . . . . . . . . . . . . . 210 9.5.4 repr () . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 9.5.5 find()andindex() . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 9.5.6 replace() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 9.6 split()andjoin() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 9.7 FormatStringsandtheformat()Method . . . . . . . . . . . . . . . . . . . . . 218 9.7.1 ReplacementFieldsasPlaceholders . . . . . . . . . . . . . . . . . . . . . 219 9.7.2 FormatSpecifier: Width . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 9.7.3 FormatSpecifier: Alignment . . . . . . . . . . . . . . . . . . . . . . . . . 223 9.7.4 FormatSpecifier: FillandZeroPadding . . . . . . . . . . . . . . . . . . 224 9.7.5 FormatSpecifier: Precision(MaximumWidth) . . . . . . . . . . . . . . . 225 9.7.6 FormatSpecifier: Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 9.7.7 FormatSpecifier: Summary . . . . . . . . . . . . . . . . . . . . . . . . . 227 9.7.8 AFormattingExample . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 vi CONTENTS 9.8 ChapterSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 9.9 ReviewQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 10 ReadingandWritingFiles 239 10.1 ReadingaFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 10.1.1 read(),close(),andtell() . . . . . . . . . . . . . . . . . . . . . 241 10.1.2 readline() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 10.1.3 readlines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 10.1.4 FileObjectUsedasanIterable . . . . . . . . . . . . . . . . . . . . . . . . 245 10.1.5 UsingMorethanOneReadMethod . . . . . . . . . . . . . . . . . . . . . 247 10.2 WritingtoaFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 10.2.1 write()andprint() . . . . . . . . . . . . . . . . . . . . . . . . . . 248 10.2.2 writelines() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 10.3 ChapterSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 10.4 ReviewQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 11 ConditionalStatements 255 11.1 ifStatements,BooleanVariables,andbool() . . . . . . . . . . . . . . . . . . 255 11.2 ComparisonOperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 11.3 CompoundConditionalStatements . . . . . . . . . . . . . . . . . . . . . . . . . . 267 11.3.1 if-elseStatements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 11.3.2 if-elif-elseStatements . . . . . . . . . . . . . . . . . . . . . . . . 270 11.4 LogicalOperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 11.5 MultipleComparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 11.6 while-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 11.6.1 InfiniteLoopsandbreak . . . . . . . . . . . . . . . . . . . . . . . . . . 278 11.6.2 continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 11.7 Short-CircuitBehavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 11.8 TheinOperator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 11.9 ChapterSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 11.10ReviewQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 12 Recursion 297 12.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 12.2 FlawedRecursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 12.3 ProperRecursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 12.4 MergeSort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 13 TurtleGraphics 311 13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 13.2 TurtleBasics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 13.2.1 ImportingTurtleGraphics . . . . . . . . . . . . . . . . . . . . . . . . . . 312 13.2.2 YourFirstDrawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 13.3 BasicShapesandUsingIterationtoGenerateGraphics . . . . . . . . . . . . . . . 317 13.3.1 ControllingtheTurtle’sAnimationSpeed . . . . . . . . . . . . . . . . . . 319 CONTENTS vii 13.4 ColorsandFilledShapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 13.4.1 StrangeErrors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 13.4.2 FilledShapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 13.5 VisualizingRecursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 13.6 SimpleGUIWalk-Through . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 13.6.1 FunctionReferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 13.6.2 Callbackfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 13.6.3 AsimpleGUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 14 Dictionaries 335 14.1 DictionaryBasics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 14.2 CyclingthroughaDictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 14.3 get() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 14.4 ChapterSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 14.5 ReviewQuestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 A ASCIINon-printableCharacters 347 Index 349 viii CONTENTS Chapter 1 Introduction 1.1 Modern Computers At their core, computers are remarkably simple devices. Nearly all computers today are built using electronic devices called transistors. These transistors serve as switches that behave much like simple light switches—they can be on or they can be off. In a digital computer each bit of information (whether input, memory, or output) can be in only one of two states: either off or on, or we might call these states low or high, or perhaps zero or one. When we say “bit,” we have in mindthetechnicaldefinition. Abitisabinarydigitthatcanbeeither0or1(zeroorone). Inavery real sense computers only “understand” these two numbers. However, by combining thousands or millions or even billions of these transistor switches we can achieve fantastically complicated behavior. Thus, rather than keeping track of a single binary digit, with computers we may be able toworkwithastreamofbitsofarbitrarylength. Foreachadditionalbitweusetorepresentaquantity,wedoublethenumberofpossibleunique valuesthequantitycanhave. Onebitcanrepresentonlytwo“states”orvalues: 0and1. Thismay seem extremely limiting, but a single bit is enough to represent whether the answer to a question is yes or no or a single bit can be used to tell us whether a logical statement evaluates to either true or false. We merely have to agree to interpret values consistently, for example, 0 represents no or false while 1 represents yes or true. Two bits can represent four states which we can write as: 00, 01, 10, and 11 (read this as zero-zero, zero-one, one-zero, one-one). Three bits have eight unique combinations or values: 000, 001, 010, 011, 100, 101, 110, and 111. In general, for n bits thenumberofuniquevaluesis2n. For n = 7 bits, there are 27 = 128 unique values. This is already more than the number of all the keys on a standard keyboard, i.e., more than all the letters in the English alphabet (both uppercase and lowercase), plus the digits (0 through 9), plus all the standard punctuation marks. So, by using a mapping (or encoding) of keyboard characters to unique combinations of binary digits, we can act as though we are working with characters when, really, we are doing nothing morethanmanipulatingbinarynumbers. We can also take values from the (real) continuous world and “digitize” them. Rather than having values such as the amplitude of a sound wave or the color of an object vary continuously, werestricttheamplitudeorcolortovarybetweenfixedvaluesorlevels. Thisprocessisalsoknown Fromthefile: intro.tex 1 2 CHAPTER1. INTRODUCTION asdigitizingorquantizing. Ifthelevelsofquantizationare“closeenough,”wecanfooloursenses into thinking the digitized quantity varies continuously as it does in the real world. Through the process of digitizing, we can store, manipulate, and render music or pictures on our computers whenwearesimplydealingwithacollectionofzerosandones. 1.2 Computer Languages Computers, though remarkably simple at their core, have, nevertheless, truly revolutionized the way we live. They have enabled countless advances in science, engineering, and medicine. They haveaffectedthewayweexchangeinformation,howwesocialize,howwework,andhowweplay. To a large degree, these incredible advances have been made possible through the development of new“languages”thatallowhumanstotellacomputerwhatitshoulddo. Theseso-calledcomputer languages provide a way for us to express what we want done in a way that is more natural to the waywethinkandyetpreciseenoughtocontrolacomputer. We, as humans, are also phenomenal computing devices, but the way we think and communi- cateisgenerallyafarcryfromthewaycomputers“think”andcommunicate. Computerlanguages provide a way of bridging this gap. But, the gap between computers and humans is vast and, for those new to computer programming, these languages can often be tremendously challenging to master. There are three important points that one must keep in mind when learning computer languages. First, these languages are not designed to provide a means for having a two-way dialog with a computer. These languages are more like “instruction sets” where the human specifies what the computer should do. The computer blindly follows these instructions. In some sense, computer languages provide a way for humans to communicate to computers and with these languages we also have to tell the computers how we want them to communicate back to us (and it is extremely rarethatwewantacomputertocommunicateinformationbacktousinthesamelanguageweused tocommunicatetoit). Second, unlike with natural languages1, there is no ambiguity in a computer language. State- ments in natural languages are often ambiguous while also containing redundant or superfluous content. Often the larger context in which a statement is made serves to remove the ambiguity while the redundant content allows us to make sense of a statement even if we miss part of it. As you will see, there may be a host of different ways to write statements in a computer language that ultimately lead to the same outcome. However, the path by which an outcome is reached is precisely determined by the statements/instructions that are provided to the computer. Note that we will often refer to statements in a computer language as “computer code” or simply “code.”2 Wewillcallacollectionofstatementsthatservestocompleteadesiredtaskaprogram.3 Thethirdimportantpointaboutcomputerlanguagesisthatacomputercanneverinfermeaning orintent. Youmayhaveaveryclearideaofwhatyouwantacomputertodo,butifyoudonotex- plicitly state your desires using precise syntax and semantics, the chances of obtaining the desired outcome are exceedingly small. When we say syntax, we essentially mean the rules of grammar 1Bynaturallanguageswemeanlanguagesthathumansusewitheachother. 2Thishasnothingtodowithasecretcodenordoescodeinthissenseimplyanythingtodowithencryption. 3A program that is written specifically to serve the needs of a user is often called an application . We will not bothertodistinguishbetweenprogramsandapplications.

Description:
Feb 2, 2014 8.4 Importing Selected Parts of a Module 13.6 SimpleGUIWalk-Through . intended to provide an in-depth Python reference 14IDLE is built using a graphics package known as tkinter which also comes with Python.
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.