152x Filetype PDF File size 0.59 MB Source: static1.squarespace.com
Introduction to computation and programming using python 2017 pdf Contents: Thanksgiving Preface1: Getting Started2: Introduction to Python3: Some Simple Numeric Programs4: Functions, Scope, and Abstraction5: Structural Types and Modifiability6: Recursion and Global Variables7: Modules and Files8: Testing and Debugging9: Exceptions and Evidence-Oriented Programming11 : A simple introduction to algorithmic complexity12: Some simple algorithms and data structures13: Graphs and more about classes14: Backpack and graphene optimization problems15: Dynamic programming16: Random walks and more about data visualization17: Stochastic programs,8 Distribution and probability Carlo modeling19: Sampling i Trust20 DATA UNDERSTANDING21: RANDOM SAMPLES AND HYPOTHESIS TESTING22: FALSE, DEEP FALSE AND STATISTICS23: DATA EXPLORATION WITH PANDAS24: MACHINE LEARNING OVERVIEW25: CLUSTERING Python26: CLASSIFICATION TECHNIQUES WITH PROGRAMMING AND AND W Applications to Computational Modeling and Data Understanding Wp Introduction to Computer Science and Programming with Python with Computational Modeling and Data Understanding Application Third Edition John W. Guttag MIT Press Cambridge, MA London, England © 2021 MIT. All rights reserved. No part of this book may be reproduced in any form by electronic or mechanical means (including photocopying, recording, or information storage and retrieval) without the written permission of the publisher. This book was created by New Best-set Typesetters Ltd. installed in Minion Pro. Library of Congress publication cataloging data names: Guttag, John, author. Title: An Introduction to Python Processing and Programming: With Applications of Computational Modeling and Data Understanding / John W. Guttag. Description: Third Edition. | Cambridge, MA: The MIT Press, [2021] | Including the index. Identifiers: LCCNContents: PrefaceAcknowledgments1: Getting Started 2: Introduction to Python3: Some Simple Numeric Programs4: Functions, Overview, and Abstraction5: Structural Types and Modifications 6: Recursion and Global Variables 7: Modules and Files 8: Testing and Debugging 9: Exceptions and Assertions10: classes and objects. -O-oriented programming11: A simplified introduction to algorithmic complexity12: Some simple algorithms and data structures13: Building and more about classes14: Backpack and graph optimization problems15: Dynamic programming16: Random walks and more Carlo simulation19: Sampling and validity20: Experimental understanding of data21 : Randomized Trials and Hypothesis Testing22: Lies Damn Lies and Statistics23: Data Mining with Pands24: A Quick Look at Machine Learning25: Clustering26: Classification Method 3.8. nd Programming using Python with a Computational Modeling and Data Understanding Application Introduction to Computer Science and Programming with Python with Computational Modeling and Data Understanding Applications Third Edition John W. Guttag MIT Press Cambridge, MA London, England © 2021 MIT All rights reserved. No part of this book may be reproduced in any form, electronic or mechanical means (including photocopying, recording, or information storage and retrieval) without the written permission of the publisher. This book was created by New Best-set Typesetters Ltd. typed in Minion Pro. Library of Congress Publications Data Name Cataloging: Guttag, John, Author. Title: An Introduction to Computer Science and Python Programming: With Applications to Computer Modeling and Data Understanding / John W. Guttag. Description: Third Edition. | Cambridge, MA: The MIT Press, [2021] | Including the index. Identifiers: LCCN| ISBN 9780262542364 (Paperback) Subjects: LCSH: Python (Computer Programming - Textbook. Programming Language) - Textbook. Classification: LCC QA76.73.P98 G88 2021 | DDC entry 005.13/3âdc23 LC available at 10 9 8 7 6 5 4 3 2 1 d_r0 | Computers My Family: Olga David Andrea Michael Addie Pierce TABLE OF CONTENTS INTRODUCTION ACKNOWLEDGMENTS 1: GETTING STARTED 2: INTRODUCING PYTHON 3: SOME SIMPLE NUMBER PROGRAMS 4: FUNCTIONS, SCOPE AND ABSTRACT 5: STRUCTURAL AND GLOBAL TYPES AGL OVERVIEW 7: MODULES AND FILES 8 : Testing and debugging 9: Exceptions and assumptions 10: Class and object -oriented programming 11: Simplified introduction to algorithmic complexity 12: Some Simple and Dackotric Algorithms1 Problems optimization of graphs 15: Dynamic programming 16: Programming of random transition of data17 visn, probability and schedule 18: simulation MONTE CARLO 2 MONTE CARLO: TRYING 20 CONCHECKHYDING AND ATTITUDE 2. FUCKING LIES AND STATISTICS 23: DATA STUDY WITH PANDAS 24: A QUICK LOOK AT TRAINING MACHINES 25: GROUPS 26: CLASSIFICATION3SCHNACHNACH INDEX Picture List Chapter 1 Figure 1-1 Flowchart eg buy lunch Chapter 2 Figure 2-1 Anaconda Start Window Figure 2-2 Spyde r Window Figure 2-3 Opera flowcharts for int and float Figure 2-4 Binding variables to objects Figure 2-5 Flowchart of a conditional statement Figure 2-6 Flowchart for iteration Figure 2-7 Integer power, the hard way Figure 2-8 Simulating a small program by hand Figure 2 -9 Using the a for statement Chapter 3 Figure 3-1 Using an exhaustive enumeration to find the square root Figure 3-2 Using an exhaustive enumeration to check for prime Figure 3-3 A more efficient primality test Figure 3-4 Approximating the square root using exhaustive list Figure 3-5 UsageFinding the Approximate Square Root 3-6. image. Using Angle Search to Estimate the Base 2 Logarithm Figure 2 3-7 Implementation of the Newton-Raphson Method 4-3. chapter Root search function -10 Using bisection_solve to fit logs Chapter 5 5-1. figure Two Lists Figure 5-2 Not two lists with the same values, but Figure 5-3 Demonstrating variability Figure 5-4 Typical list methods Figure 5-4 5-5 Applying functions to list items Figure 5-3 Figure 5-6 General operations with for Sequence Types 5-7 Comparison of Sequence Types 5-8 Some String Methods 2 6-4 Palindrome Testing Figure 6-5 Visualization Code Palindrome Testing Figure 6-6 Using a Global Variable Chapter 7 Figure 7-1 Some Code Related to Circles and for spheres Figure 7-2 Typical file access functions Chapter 8 Figure 8-1 Boundary condition testing Figure 8-2 No first error Figure 8-3 Program with errors Chapter 9 Figure 9-1 Using exceptions to control flow Figure 9- 2 Flow control without retry , except Figure 9-3 Deriving Calculations Chapter 10 Chapter 10 10-1. Figure Class Int_set Figure 10-2 Using Magic Methods Figure 10-1 10-3 Class Person Figure 10-4 Class MIT_person Figure 10-5 Two Student Types Figure 10-6 Class Grades Figure 10-7 Creating a Grade Report Figure 10- 8 Hiding information in classes Figure 10-9 Figure 10-10 The new version of the get_students mortgage databaseFigure 11-5 Intersection List Implementation Figure 11-6 Power Generation Figure 11-7 Constant, Logarithmic and Linear Growth Figure 11-8 Linear, Logarithmic and Quadratic Growth Figure 11-9 Quadratic and Exponential Growth Chapter 12 Figure 12-1 List Implementation Figure Figure 12-2 Linear Ordered List Search Figure 12-3 Recursive Binary Search Figure 12-4 Selection Sort Figure 12-5 Merge Sort Figure 12-6 Name List Sorting Figure 12-7 Chapter 13 Dictionary Implementation Using Hash Function Figure 13-1 Simple Graph Figure 13-2. Figs. Contents of Jane.png (left) and FigureAddie.png (right) files -12 Costs of different types of mortgages over time 13-13 Balance and net costs of different types of mortgages Figure. 13.-14. figs. Modeling the spread of an infectious disease Fig. Figure 13-15 Infection History Chart Function Figure 13-16 Creating a Chart with One Set of Parameters Figure 13-17 Static Infection Count Chart Figure 13- 18 Interactive Chart with Initial Slider Values Figure 13-19 Interactive Chart with Changed Slider Values Chapter 14 Figure 14- 1. Item List Figure 14-2. Class Element Figure 14-3. Implementation of the Greedy Algorithm Figure 14-4. Using a greedy algorithm to select elements 14.-6 Königsberg (left) and the Euler bridgemap (right) Figure 14-7 Nodes and edges Figure 14-8 Classes of graphs and digraphs Figure 14-9 Figure 14-9 Depth-first path search Figure 14-10 Testing depth-first search code Figure 14-11 Breadth-first search - shortest path finding chapter 15 Figure 15-1 Recursive Fibonacci bell tree Figure 15-2 Fibonacci implementation with note Figure 15-3 Element table with values and weights Figure 15-4 Knapsack decision tree Figure 15-5 Using knapsack decision tree Figure 15 Figure 15 -7 Dynamic Image Programming Backpack Solution Figure 15-8. Figure 16-1 Efficiency of a Dynamic Programming Solution Chapter 16 Figure 16-1 Extreme Farmer Figure 16-2 Location and Terrain Classes Figure 16-3 Class Definition Drunk Figure 16-3 16-4 Drunk Walking (Wrong) Figure 16-6 Subclasses of the Drunk Base Class Figure 16-7 Style Iteration Figure 16-8 Drawing Figure 16-9 Average Distance for Different Types of Drinkers Figure 16-15 Strange Movement Chapter 17 Figure 17-1 Rolling a Dice Figure 17-2 Tossing a Coin 17-3. image. Regression to the mean 17-4. image. Regression to the Mean Illustration 17-5. image. Chart of coin toss results 17-6. image. The Law of Large Numbers in Action Figure 17-7. Law of Large Numbers in Action Figure 17-8 Dispersion and Standard Deviation 9 Utility Function in Flip Simulation Figure 17-10 Coin Flip Simulation Figure 17-10 Coin Flip Simulation 17-11 Heads/Tails Convergence Figure 17-12 Absolute Differences Figure 17-13 Eagle Mean and standard deviation -Tails Figure 17-14 Coefficient of variation Figure 17-15 Final flip_plot Figure 17-16 Coefficient of variation head/tail and abs (head âFigure 17-23 PDF for Gaussian Distribution Figure 17-24 Normal Distribution Figure 17-25 Absolute Value x Plot Figure 17-26 Empirical Rule Test Figure 17-27 Plotting with Error Bars Figure 17-28 Calculation with Error Bars Figure 17-29 Exponential Molecular Clearance Figure 17-30 Exponential Decay Figure 17-31 Exponential Distribution Plot with Logarithmic Axis Figure 17-33 Geometric Distribution Figure 17-32 Construction of Geometric Distribution Figure 17-34 Jash Simulation Table Figure 17-35 World Series Simulation Figure 17. -36 Win Probability in 7 Game Series Chapter 18 18-1. Figure Testing Pascal Analysis Figure 18-2 Craps_game Class Figure 18-3 Craps Game Simulation Figure 18-4 Using Search Figure 18-5 Unit Circle Squared Figure 18-6 Calculus - Chapter 19 Figure 19-1 First Rows bm_results2012. csv Figure 19-2 Reading and Displaying Data Boston Marathon Figure 19-3 Boston Figure 19-4 Marathon Finish Times Figure 19-5 Small Sample Analysis 19-6. image. Effects of Dispersion on Mean Estimates Figure 19-7 Calculating and Displaying Sample Means Figure 19-8 Sample Means 19-9. Figure Averaging a continuous matrix 19-10. Figure CLT Figure 19-11. Production Plot with Error Bars Figure 19-12 Completion Time Estimates with Error Bars Figure 19-13 Standard Error of the Mean Figure 19-14 Sample Standard Deviation Vs. population standard deviation 19-15. image. Sample standard deviation Figure 19-16. Determining the Population Mean 10,000 Times Chapter 20 20-1. Figure Classic Experiment 20-2. image. Retrieving data from a set Figure 20-3 Displaying data Figure 20-4 P spring movementHuge. Limit Bullet Experiment Data Figure 20-11. Bullet trajectory chart. Figure 20-12. Trajectory chart. Figure 20-13. R2 calculation. to semilog Figure 20-18 Using Polyfit for exponential fitting Figure 20-19 Fitting an exponential function Chapter 21 Figure 21-1 Finish times for cyclists Figure 21-2. Temperature difference in January 2020 with the 1981–2010 average 145 Fig. 21-3. Plotting a t-Distribution Examples Figure 21-7 Probability of a p-value Figure 21-8 Lindsey Game Modeling Figure 21-9 Proper Game Modeling Figure 21- 10 Effect of Sample Size on p-Value Figure 21-11 Country Comparison of Average Completion Time for a Selected Figure 21-12 Testing Multiple Hypotheses 21-13 The sun exploded? Chapter 22 Figure 22-1 Housing prices in the Midwest. Figure 22-2. Housing price chart. Figure 22-3. Another look at housing prices. ? Figure 22-7 Statistics for the Anscomb quartet Figure 22-8 Data for the Anscomb quartet Figure 22-9 Social Security vs. Quartet full-time employment Figure 22-10 Sea ice in the Arctic Figure 22-11 Rise in US Internet use Figure 22-12 Relevance Professor surprised by students throwing chalk Figure 22-13 Probability of having 48 anorexic girls in June Figure 22 - 14 months Probability births of 48 anorexics in some Chapter 23 Figure 23-1 wwc APandas data frame linked to a variable Figure 23-2 Sample CSV file Figure 23-3 Creating a dictionary that maps years to temperature data Figure 23-4 Creating a year-by-year data frame Figure 23-5 Creating year-by-year charts for temperature measurements Figure 23- 6 Annual mean and minimum temperatures Fig. 23-7 Moving average of minimum temperatures Fig. 23-8 Average temperatures of selected cities Fig. 23-9 Differences in extreme temperatures Fig. 23-10 Global consumption of fossil fuels Chapter 24 Fig. 24- 1 Two sets of names Fig. 24 -2 Assigning a trait vector to each name Figure 24-3 Feature vector/tag pairs for presidents Figure 24-4 Names, traits and designations for various animals Figure 24-5 Displaying distance metrics Figure 24-6 Minkowski distance Figure 24-7 Class of animals Figure 24-8 Create a table of distances between pairs of animals Figure 24-9 Dist de between three animals Figure 24-10 Distances between c with four animals Figure 24-11 Representation of the distances according to the difference in the annuity function Chapter 25 Figure 25-1 Height, weight and shirt color Figure 25-2 Example class Figure 25-3 Classification classes Figure 25-4 K-Means Clustering Figure 25 -5 Find Best K-Means Clustering Figure 25-6 K-Means Test Figure 25-7 Examples from two distributions Figure 25-8 Rows obtained by calling contrived_test(1, 2, True ) are printed Figure 25-9 Generating points from three distributions Figure 25-10 Points from three overlapping Gaussians Figure 25-11 Mammalian dentition in dentalFormulas.csv 25-12 Reading and processing CSV files Fig. 25-13 Attribute scaling Fig. Fig. 25-14 Start of CSV file for classifying mammals by diet Fig. 25-15 Associated grouping with labels Fig. 26 Fig. Figure 26-1 Voter Preference Charts Figure 26-2 Confusion Matrix Figure 26-3 Complexes res model Figure 26-4 Classifier evaluation functions Figure 26-5 First rows of bm_results2012.csv Figure 26-6 Examples of creating and splitting data into training sets and Figure 26-7 findingNeighbors Figure 26-8 Distribution-Based Classifier Figure 26-9 Good k-search Figure 26-10 Choosing a k-value Figure 26-11 Male and Female Linear Regression Models Figure 26-12 Creating and Plotting Linear Regression Models Figure 26-13 Using Figure 26-14 Using Sklearn to perform multi-class logistic regression Figure 26-15 Two-class logistic regression example Figure 26-16 Using logistic regression to predict AUROC gender curves and find Figure 26-18 ROC curve and AUROC graph 26-19 Passenger class Figure 26-20 Titanic Data Reading and Sample List Generation Online Open Courses (MOOCs) are offered by edX and MITx. The first edition of the book was based on one semester course. However, as time went on, I couldn't resist adding more material than would fit in one semester. The current issue is suitable for a two-semester or three-quarter introductory sequence to computer science. The book is intended for 1) readers with little or no programming experience who want to understand the computational approach to problem solving, and 2) more experienced programmers who want to learn how to use calculus to model things or explore data. We focus on width, not depth. The goal is to give readers a brief introduction to many topics so that they have an idea of what is possible when it comes to thinking about how to use counting to achieve your goal. This is not a book for lovers of calculus, however. It's hard and rigorous. Readers who really want to master this material will need to spend a lot of time and effort learning how to bend the computer to their will. The main purpose of this book is to help readers become familiar with productive useComputer techologies. They must learn to use computational thinking to formulate problems, build computational models, and manage the process of extracting information from data. The main knowledge they draw from this book is the art of solving computational problems. We have decided not to include tasks at the end of the chapter. Instead, we have placed "finger exercises" in convenient places in the sections. Some of them are relatively short and are intended to allow readers to confirm that they have understood the material they have just read. Some of them are more complex and suitable for exam questions. And others are complex enough to be useful as homework. Chapters 1 to 13 cover material commonly found in an introductory computer science course, but the presentation is unconventional. We combine four parts of the material: programming fundamentals, the Python 3 programming language, problem solving techniques, and computational complexity. We'll cover most of Python's features, but the focus will be on what you can do with the programming language, not the language itself. For example, by the end of Chapter 3, the book covers only a small part of Python, but already introduces the concepts of exhaustive enumeration, guess-and-test algorithms, partition search, and efficient approximation algorithms. We introduce you to Python functions throughout the book. Similarly, we introduce aspects of programming techniques throughout the book. The goal is to help readers learn Python and learn how to become a good programmer by using computation to solve interesting problems. These chapters have been redesigned to move more smoothly and include more exercises than the corresponding chapters in the second edition of this book. Chapter 13 provides an introduction to rendering in Python. This topic is not often covered in introductory courses, but we believe that learning to create visualizationsis an important skill to include in an introductory computer science course. This chapter contains material not included in the second edition. Chapters 14- 26 are about using computers to understand the real world. They include material that we believe should become commonplace in the second year of computer science studies. They assume the reader has no knowledge of mathematics beyond school algebra, but enjoys rigorous thinking and is not intimidated by mathematical concepts. This part of the book covers topics not covered in most introductory texts: data visualization and analysis, stochastic programming, simulation models, probabilistic and statistical reasoning, and machine learning. We believe that this material will be more relevant to most students than what is usually covered in a second computer science course. With the exception of Chapter 23, the material in this part of the book focuses on conceptual issues rather than programming. Chapter 23 is an introduction to pandas not covered in previous issues. The book has three overarching themes: systematic problem solving, the power of abstraction, and calculus as a way of thinking about the world. By the time you finish reading this book, you should: Learn Python to express computations Learn a systematic approach to organizing, writing, and debugging medium-sized programs Develop an informal understanding of the complexity of data processing Gain insight into the process. move from an ambiguous problem statement to a computational formulation of a problem solving method, learn a range of useful algorithmic and problem reduction techniques, learn to use randomness and simulations to explain problems that are not easy to solve. -Form solutions and learn to use computer tools (including simple statistical, visualization and machine learning tools) to model and understand data.is inherently difficult work. Just like "there is no silver bullet in geometry", there is no silver bullet in programming. If you really want to learn the material, reading the book is not enough. At the very least, you should be doing finger exercises related to coding. If you want to try more advanced tasks, try some of the tasks available at . -programming-in-python-fall- 2016/ and - 2016/. 1 This was Euclid's supposed answer around 300 BC. at the request of King Ptolemy for an easier way to learn mathematics. ACKNOWLEDGMENTS The first edition of this book grew out of a series of lecture notes I wrote while teaching at MIT. The course, and therefore this book, was created thanks to the contributions of faculty colleagues (in particular, Ana Bell, Eric Grimson, Srinivas Devadas, Fredo Durand, Ron Rivest, and Chris Terman), teaching assistants, and students who participated in the course. David Guttag overcame his distaste for computer science and revised several chapters of the first edition. Like all successful professors, I owe a lot to my graduates. Guha Balakrishnan, Davis Blalock, Joel Brooks, Ganeshapillay Gartiban, Jen Gong, Cathy Lewis, Yun Liu, Jose Javier Gonzalez Ortiz, Anima Singh, Divya Shanmugam, Jenna not only did a lot of research (and let me give credit for that). Vince and Amy Zhao provided helpful comments on various versions of this manuscript. Special thanks to Julia Sussman, P.P.A., who edited the first two editions of this book, and Lisa Ruffolo, who edited the current edition. Both Julie and Lisa were employees who read the book through the eyes of a student and told me what to do.what should be done and what could be done if I had the time and energy to do it. They buried me in "recommendations" that were too good to ignore. Finally, thanks to my wife Olga for motivating me to finish and freeing me from various household chores to work on the book. 1â GETTING STARTED The computer does two and only two things: it performs calculations and stores the results of those calculations. But it does both very well. A typical computer lying on a desk or in a backpack performs about 100 billion calculations per second. It's hard to imagine how fast it really is. Think of holding the ball one meter off the floor and letting it go. Your computer may have performed over a billion instructions before it fell to the floor. When it comes to memory, a small computer can have hundreds of gigabytes of memory. How big is it? If a byte (the number of bits, usually eight, needed to represent one character) weighed one gram (it does not weigh), 100 gigabytes would weigh 100,000 metric tons. For comparison, this is the combined weight of about 16,000 African elephants2. For much of human history, computation was limited by the speed at which the human brain could calculate and how well the human hand could record the results of the calculations. This meant that only the smallest problems could be computationally attacked. Even with the speed of modern computers, some problems are still beyond today's computational models (such as fully understanding climate change), but more and more problems can be solved computationally. We hope that by the time you've finished reading this book, you'll feel comfortable using computational thinking to solve many of the problems you face in college, at work, and even in everyday life. What do we mean by computational thinking? All knowledge can be considered declarative or mandatory. Declarative knowledge consists in stating a fact.B. "The square root of x is a number y such that y*y = x" and "You can travel from Paris to Rome by train." Unfortunately, they don't tell us anything about how to find the square root or how to take the train from Paris to Rome. Imperative knowledge is the knowledge of "how to" or recipes for obtaining information. Hero of Alexandria was the first to document a way to calculate the square root of a number. His way of finding the square root of a number, let's call it x, can be summarized as follows: 1. Start with a guess, g. 2. If g*g is close enough to x, stop and say g is the answer. 3. Otherwise, create a new estimate by averaging g and x/g, ie. HOUR. (gx/g)/2. + 4. Using this new estimate, which we will again call g, repeat the process until g*g is close enough to x. Try to find the square root of 25. 1. Set g to any value like B. 3. 2. Decide that 3*3 3. Don't put g = 9 close enough to 25. to (3 + 25/3)/ 2 = 5.67.4 4. Decide that 5.67*5 .67 25. 5. Set g = 32.15 is still not close enough to (5.67 + 25/5.67)/2 = 5.04 6. Decide we find that 5.04*5.04 = 25.4 is close enough to stop and declare 5.04 to be a reasonable approximation of the square root of 25. Note that the description of the method is a series of simple steps along with a control flow that determines when each step should be performed. Such a description is called an algorithm5. The algorithm we used to approximate the square root is an example of an "evaluate and verify" algorithm. It is based on the fact that it is easy to check whether the estimate is good enough or not. More formally, an algorithm is a finite list of instructions that describe a sequence of calculations that, when performed on a set of inputs, go through a sequence of well-defined states and finally produce a result. The algorithm is like a recipe from a cookbook: 1. Reheat the pudding mix. 2. Stir. 3. Dip the spoon into the pudding. 4. Remove the spoon and run your finger along the back of the spoon. 5. When it's clearRemove the rest of the cream from the heat and let it cool. 6. Otherwise, repeat. The recipe contains several tests to determine the completion of the process, as well as instructions on the order in which the instructions should be executed, sometimes jumping to a specific instruction based on the test. So how do you capture the idea of a recipe in a mechanical process? One way is to develop a machine specifically designed to calculate square roots. Strange as it may sound, the earliest computing machines were actually fixed-program computers, meaning they were designed to solve a specific mathematical problem, such as calculating the trajectory of an artillery shell. One of the first computers (built in 1941 by Atanasov and Berry) solved systems of linear equations, but could do nothing else. Alan Turing's bomb machine, developed during World War II, was designed to break the German Enigma codes. Some simple computers still use this approach. For example, a four-function calculator6 is a computer with a fixed program. It can do basic arithmetic, but it can't be used as a text editor or run video games. To change the program of such a machine, you need to change the circuit. The first truly modern computer was the Manchester Mark 1.7. It differed from its predecessors in that it was a computer with a stored program. Such a computer stores (and processes) a sequence of instructions and has components that execute any instructions in that sequence. At the heart of such a computer is an interpreter that can execute any valid set of instructions and thus can be used to compute anything that can be described by those instructions. The result of the calculation can also be a new sequence of instructions, which can then be executed by the computer that generated it. In other words, the computer can program itself. Both the program and the data it manipulates are stored in memory. A program counter usually points to a specific location in memory and the calculation begins with an executionat this time. In most cases the interpreter will just move on to the next command in the sequence, but not always. In some cases, it will run a test, and based on that test, execution may jump to another point in the command sequence. This is called control flow, and it is essential for us to write programs that perform complex tasks. People sometimes use flowcharts to show control flow. By convention, we use rectangular boxes to indicate a processing step, a diamond to indicate a check, and arrows to indicate the order in which the steps are performed. Figure 1-1 is a flowchart showing the dinner approach. Figure 1-1 Dinner Flow Chart Returning to the recipe metaphor, a good cook can create an unlimited number of delicious dishes by combining them in many different ways. Similarly, with a small fixed set of primitive functions, a good programmer can create an unlimited number of useful programs. This is what makes programming such an amazing job. To create recipes or sequences of instructions, we need a programming language to describe them, a way to give the computer its steps. In 1936, British mathematician Alan Turing described a hypothetical computing device called the Universal Turing Machine. The machine had unlimited memory in the form of "tape" on which zeros and ones were written, and some simple, primitive instructions for moving, reading, and writing to the tape. The Church-Turing Theorem states that if a function is computable, a Turing machine can be programmed to compute it. The important thing is the "if" in the Church-Turing theorem. Not all problems have computational solutions. For example, Turing showed that it is impossible to write a program that takes any program as input and returns true if and only if the input program runs forever. This is called a hang-up problem. The Church-Turing thesis leads directlyThe concept of Turing completeness. A programming language is called Turing complete if it can be used to model a universal Turing machine. All modern programming languages are Turing complete. As a result, anything that can be programmed in one programming language (such as Python) can be programmed in any other programming language (such as Java). Of course, some things are easier to program in a certain language, but in terms of processing power, all languages are almost the same. Fortunately, no programmer needs to create programs from primitive Turing instructions. Instead, modern programming languages offer a wider and more convenient set of primitives. However, the basic idea of programming as a process of creating a sequence of operations is key. No matter what set of primitives you have and what methods you use to create them, the best and worst things about programming are the same: the computer will do exactly what you tell it to do, no more, no less. This is good because it means you can make your computer do all sorts of fun and useful things. This is bad, because if it doesn't do what you want, you usually have no one to blame but yourself. There are hundreds of programming languages in the world. There is no better language. Different languages are better or worse for different types of applications. For example, MATLAB is a good language for working with vectors and matrices. C is a good language for writing programs that manage data networks. PHP is a good language for building websites. And Python is a great general-purpose language. Every programming language has a set of primitive constructs, syntax, static semantics, and semantics. Like a natural language such as English, primitive constructs represent words, syntax describes which strings of words form well-formed sentences, static semantics determines which sentences are correct.and the semantics determine the meaning of these sentences. The primitive constructs in Python include literals (like the number 3.2 and the string "abc") and infix operators (like + and /). The syntax of a language determines which strings and characters are correctly formed. For example, in English, the string "Cat dog boy". is not a syntactically valid sentence, since English syntax does not accept sentences of the form . In Python, the primitive sequence 3.2 + 3.2 is syntactically well-formed, but the sequence 3.2 3.2 is not. Static semantics determine which syntactically valid strings have a value. For example, take the lines "He runs fast" and "I run fast". Each of them is of the form , which is a syntactically acceptable sequence. However, none of these are valid in English, due to the rather odd rule that for a regular verb, if the subject of the sentence is in the first or second person, the verb doesn't end in "s" but does end in "s" when the subject is in the third person singular yes. These are examples of static semantic errors. The semantics of a language assign meaning to any syntactically correct sequence of characters that has no static semantic errors. In natural languages, the semantics of a sentence can be ambiguous. For example, the phrase "I cannot praise this student highly enough" can be both flattering and judgmental. Programming languages are designed in such a way that every legal program has exactly one value. Although syntax errors are the most common type of error (especially for those learning a new programming language), they are the least dangerous. Any reputable programming language will detect all syntax errors and prevent users from running a program with just a single syntax error. Also, in most cases, the language system indicates the location of the error clearly enough for the programmer to fix it without thinking. Recognize and resolve static semanticsis more complicated. Some programming languages, such as some programs such as Java, perform many static semantic checks before running the program. Others, such as Others, such as C and Python (unfortunately), perform relatively fewer static semantic checks before running the program. Python performs a significant amount of semantic checking at runtime. If the program has no syntax errors and no static semantic errors, then it has meaning, i.e. H. it has semantics. Of course, it may not have the semantics that its creator intended. If a program means something other than what its creator thinks, bad things can happen. What can happen if a program has a bug and behaves unintended? There may be an accident, namely H. stops the run and makes it clear that he has done so. In a properly designed computer system, when a program crashes, the entire system is not damaged. Unfortunately, some very popular computer systems do not have this nice feature. Almost everyone who uses a personal computer has run a program that managed to require a restart of the entire system. It could go on and on and never stop. If you don't have a rough idea of how long the program should run, it can be difficult to determine this situation. It can be run all the way and give an answer that can be right or wrong. Each of these results is bad, but the last one is definitely the worst. When a program appears to be doing the right thing but isn't, bad things can happen: property can be lost, patients can receive lethal radiation therapy, planes can crash. Whenever possible, programs should be written in such a way that it is obvious that they do not work correctly. We'll discuss how to do this throughout the book. Finger Exercises: Computers can be very annoying. If you don't tell them exactly what to do, they are more likely to do it wrong. Try to write an algorithm for driving between two destinations. Writethe way you would treat a human, and then imagine what would happen if that human were as stupid as a computer and executed the algorithm exactly as written. (For a fun illustration of this, see the video 1.1. — terms introduced in Declarative Knowledge. The corrected algorithm-program for calculating mandatory knowledge is saved. program computer program interpreter flow counter control flowchart programming language universal Turing machine halting problem Church-Turing completeness of the thesis Turing literals infix
no reviews yet
Please Login to review.