Recitation 7 Programming for Engineers in Python.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Plotting Selim Aksoy Bilkent University Department of Computer Engineering
Introduction to Matlab
Python Crash Course Accuracy 3 rd year Bachelors V1.0 dd Hour 7.
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 3.
16-May-15 Sudden Python Drinking from the Fire Hose.
Recitation 4 Programming for Engineers in Python.
Get number The ginput command creates crosshairs. When the user clicks the x,y values of the crosshairs are returned.
By. What advantages has it? The Reasons for Choosing Python  Python is free  It is object-oriented  It is interpreted  It is operating-system independent.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Structure of program You must start with a module import# You must then encapsulate any while loop in a main function at the start of the program Then.
Recitation 1 Programming for Engineers in Python.
PYTHON PLOTTING CURVES CHAPTER 10_5 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
 1 Basic Data Visualization. IPython An interactive shell to execute Python script. Run from a shell; ipython 2.
IMAGE PROCESSING LIBRARY (PIL) This is a package that you can import into python and it has quite a few methods that you can process image files with.
Chapter 5 Review: Plotting Introduction to MATLAB 7 Engineering 161.
Lists in Python.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
Introduction to Python Session 2: Beginning Numerical Python and Visualization Jeremy Chen.
418512: Computer Programming Languages Lecture 7 Pramook Khungurn TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.: A AAAA.
Organizing Quantitative Data: The Popular Displays
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Scientific Computing with NumPy & SciPy NumPy Installation and Documentation  Not much on the home page—don’t buy the guide, it’s.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Xin Liu Feb 11, * Part 1 1. What value does s have, after this code is run? s = '*' s = s + s s = s + s + s (A) '**' (B) '***' (C) '****' (D) '*****'
Variables and Functions. Open your Encoder program Let’s begin by opening the “Labyrinth Auto Straight” code. Save this file as Labyrinth with variables.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
12/9/2010 Course A201: Introduction to Programming.
Python Functions.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #001 (January 17, 2015)
A string is an array of characters Strings have many uses in MATLAB Display text output Specify formatting for plots Input arguments for some functions.
Hossain Shahriar Announcement and reminder! Tentative date for final exam need to be fixed! We have agreed so far that it can.
Computing Science 1P Large Group Tutorial 13 Simon Gay Department of Computing Science University of Glasgow 2006/07.
Python Crash Course Numpy & MatplotLib Sterrenkundig Practicum 2 V1.0 dd Hour 3.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
Matplotlib SANTHOSH Boggarapu.
Practical Kinetics Exercise 2: Integral Rate Laws Objectives: 1.Import Experimental Data (Excel, CSV) 2.Fit to zero-, first-, and second-order rate laws.
ITERATION. Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that.
Python & NetworkX Youn-Hee Han
PROGRAMMING USING PYTHON LANGUAGE ASSIGNMENT 1. INSTALLATION OF RASPBERRY NOOB First prepare the SD card provided in the kit by loading an Operating System.
Numerical and Scientific Computing Part 2
PH2150 Scientific Computing Skills
Lecture 8: Python Writing Scripts in GIS
Introduction to Python
IPYTHON AND MATPLOTLIB Python for computational science
Functions CIS 40 – Introduction to Programming in Python
Engineering Innovation Center
Python NumPy AILab Batselem Jagvaral 2016 March.
PH2150 Scientific Computing Skills
Count Controlled Loops (Nested)
Python plotting curves chapter 10_5
Matplotlib.
Numpy (Numerical Python)
Writing Functions( ) (Part 4)
Suppose I want to add all the even integers from 1 to 100 (inclusive)
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Python Basics Wen-Yen Hsu, Hsiao-Lung Chan Dept Electrical Engineering
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Matplotlib and Pandas
Programming with data Lab 3
EE 194/BIO 196: Modeling biological systems
Topic: Iterative Statements – Part 2 -> for loop
Class code for pythonroom.com cchsp2cs
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Recitation 7 Programming for Engineers in Python

Plan Plotting Debugging The Code 2

Plotting - Example 3

Plotting 4 To install matplotlib package, just click matplotlib downloadmatplotlib download Simple example import matplotlib.pyplot as plt # shorten the module’s name plt.plot([1,2,3,4]) plt.ylabel(‘some numbers') plt.show(False) # False is required when calling ‘show’ from the shell A list represents a vector! A single input list = y values x vector - from 0

Plotting 5 Create square numbers plt.plot([1,4,9,16]) Choose correct x values – two lists! plt.plot([1,2,3,4], [1,4,9,16], ‘ro’) Fix ranges of axes plt.axis([0, 6, 0, 20]) Order: [xmin, xmax, ymin, ymax]

Line Styles 6 The entire description

Plot Continuous Values 7 Show cos(x) of x values 0-5, with 0.1 step size. How is this range created? >>> range(0, 5, 0.1) TypeError: range() integer step argument expected, got float. Use numpy! import numpy as np x = np.arange(0, 5, 0.1)

Numpy Arrays - Creation 8 >>> A= np.array([[1, 2, 4, 8], [16, 32, 64, 128]]) # 2x4 matrix array([[1, 2, 4, 8], [16, 32, 64, 128]]) >>> B= np.arange(8).reshape(2, 4) # reshaped into 2x4 matrix array([[0, 1, 2, 3], [4, 5, 6, 7]]) >>> np.zeros((2, 4)) # create a 2x4 matrix of zeros array([[0., 0., 0., 0.], [0., 0., 0., 0.]])

Numpy Arrays 9 >>> np.ones((2, 4)) # create a 2x4 matrix of ones array([[1., 1., 1., 1.], [1., 1., 1., 1.]]) >>> A– B # elementwise subtraction array([[1, 1, 2, 5], [12, 27, 58, 121]]) >>> B**2 array([[0, 1, 4, 9], [16, 25, 36, 49])

Numpy Arrays - Arithmatics 10 >>> A*B # elementwise product array([[ 0, 2, 8, 24], [ 64, 160, 384, 896]]) >>> np.dot(A, np.transpose(B)) # dot product, dims must agree array([[ 34, 94], [ 544, 1504]]) >>> B.cumsum(axis=1) # cumulative sum along each row array([[ 0, 1, 3, 6], [ 4, 9, 15, 22]])

Plot Continuous Values 11 Left plt.plot(x, np.cos(2*np.pi*x), 'r--') Right x1 = np.arange(0, 10, 0.1) x2 = np.arange(0, 10) plt.plot(x1, np.exp(x1), 'b-', x2, np.exp(x2), 'ro')

Explaining the Data 12 How can I know what a plot refers to? plt.xlabel(‘radians’) plt.ylabel(‘cosine’) plt.title(‘Cosine Function’)

Subplots 13

Subplots 14  subplot(numRows, numCols, plotNum) >>> subplot(3, 2, 4) Lose the commas if rows and cols < 10 plt.subplot(211) plt.plot(x, np.cos(2*np.pi*x), 'r--') plt.subplot(212) x1 = np.arange(0, 10, 0.1) x2= np.arange(0, 10) plt.plot(x1, np.exp(x), 'b-', x2, np.exp(x2), 'ro') Plot 1Plot 2 Plot 3Plot 4 Plot 5Plot 6

Show Histograms 15 # create data mu = 100 sigma = 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data plt.hist(x, 50, normed = 1, facecolor='g') # arrange plot plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.axis([40, 160, 0, 0.03])

Show Histograms 16

∏ Estimation 17  Rings a bell? (recitation 4) def estimate_pi(error): term = 1 summ = 0 k = 1 while term > error: term = 1.0/k**2 summ += term k += 1 summ = sqrt(summ*6.0) return summ

∏ Estimation 18  Create estimations of π by different error values pi_est = [] err_val = range(2, 12) err_vec = [10**(-x) for x in err_val] for err in err_vec: pi_est.append(estimate_pi(err))

∏ Estimation – Build Plot 19 margin = 0.01 plt.plot([err_val[0]-1, err_val[-1]+1],[pi, pi], 'b-', err_val, pi_est, 'go') plt.axis([err_val[0]-1, err_val[-1]+1, min(pi_est)- margin, max(pi_est)+ margin ]) # document plot plt.xlabel('-log10 error') plt.ylabel('Estimation') plt.title('Pi Estimation') plt.legend(('python pi','estimation'), loc=4) # show plot and save as an image plt.show() plt.savefig('pi.png')

∏ Estimation - Result 20

How to Find Bugs 21

22 A unit is the smallest testable part of an application. The goal of unit testing is to isolate each part of the program and show that the individual parts are correct Pros: simplifies integration with other units, “living documentation” (how to use the code), helps design. The hw tests are examples of unit testing How to Find Bugs

23  Mission: create 1000 lists of 25 guesses (random numbers) from 0,1,2,3 nSuits, nCards, nPlayers = 4, 25, 1000 players_guess=[] cards_list=[0]*nCards # create guesses for player in range(nPlayers): for card in range(nCards): # create one guess cards_list[card ]= random.randrange(0,nSuits) players_guess.append(cards_list)

How to Find Bugs 24 Investigate the lists created: >>> players_guess[0] [1, 1, 3, 3, 2, 2, 2, 3, 1, 2, 3, 1, 3, 0, 0, 3, 2, 0, 2, 0, 3, 2, 2, 3, 2] >>> players_guess[1] [1, 1, 3, 3, 2, 2, 2, 3, 1, 2, 3, 1, 3, 0, 0, 3, 2, 0, 2, 0, 3, 2, 2, 3, 2] >>> players_guess[2] [1, 1, 3, 3, 2, 2, 2, 3, 1, 2, 3, 1, 3, 0, 0, 3, 2, 0, 2, 0, 3, 2, 2, 3, 2] Oh, No, Bug! How to Find Bugs

25 Trace the code step by step. In this case – by iterations. We begin by tracing the outer loop: for player in range(3): # 1000 is a lot! for card in range(nCards): cards_list[card ]= random.randrange(0,nSuits) players_guess.append(cards_list) print cards_list How to Find Bugs

26 Output: [2, 3, 3, 0, 2, 1, 2, 0, 2, 3, 2, 2, 2, 1, 1, 0, 0, 2, 2, 1, 2, 3, 0, 0, 3] [1, 2, 3, 3, 2, 0, 0, 1, 0, 0, 1, 2, 2, 3, 3, 1, 2, 1, 0, 0, 2, 0, 1, 3, 3] [2, 2, 2, 0, 3, 1, 3, 2, 1, 2, 3, 1, 2, 3, 1, 2, 1, 1, 0, 1, 2, 2, 0, 2, 1] The problem is not here. What is players_guess? >>> players_guess [[2, 2, 2, 0, 3, 1, 3, 2, 1, 2, 3, 1, 2, 3, 1, 2, 1, 1, 0, 1, 2, 2, 0, 2, 1], [2, 2, 2, 0, 3, 1, 3, 2, 1, 2, 3, 1, 2, 3, 1, 2, 1, 1, 0, 1, 2, 2, 0, 2, 1], [2, 2, 2, 0, 3, 1, 3, 2, 1, 2, 3, 1, 2, 3, 1, 2, 1, 1, 0, 1, 2, 2, 0, 2, 1]] Notice anything? How to Find Bugs

27 Ok, we found the problem, but what is the reason? And the solution? Main suspect: players_guess.append(cards_list) Is this drawing correct? How to Find Bugs players_guess cards_list

28 There is only one list – which is mutated every iteration.  Found the problem. Solution? players_guess cards_list How to Find Bugs

29 for player in range(nPlayers): # create cards list inside the loop cards_list=[0]*nCards for card in range(nCards): cards_list[card]= random.randrange(0,nSuits) players_guess.append(cards_list) How to Find Bugs

30  Mission: replace first and last character in a string def switch(s): first = s [0] last = s [-1] s = s.replace(s[0], last ) s = s.replace(s[-1], first ) return s >>> switch(‘abcd’) abca >>> switch(‘banana’) bbnbnb How to Find Bugs

31 Add ‘print’ def switch(s): first = s [0] last = s [-1] s = s.replace(s[0], last ) s = s.replace(s[-1], first ) return s How to Find Bugs

32 >>> switch('abcd') 'abca' >>> switch('banana') 'bbnbnb‘  Let’s add ‘print’ commands inside switch: print s s = s.replace(s[0], last ) print s s = s.replace(s[-1], first ) return s How to Find Bugs

33 >>> switch('abcd') abcd dbcd 'abca' >>> switch('banana') banana aanana 'bbnbnb‘  Observations? How to Find Bugs

34 Observation: replace changes all occurances of the character in the string – we only want one specific change. >>> help(str.replace) replace(...) S.replace(old, new[, count]) -> string Solution: s = s.replace(s[0], last, 1 ) s = s.replace(s[-1], first, 1 ) How to Find Bugs

35 >>> switch('abcd') abcd dbcd 'abcd' >>> switch('banana') banana aanana 'banana‘ Observation: The first letter is changed twice! Solution: replace doesn’t work for us, use a different method! How to Find Bugs

36 New code: return s[-1]+s[1:-1]+s[0] >>> switch('abcd') 'dbca' >>> switch('banana') 'aananb’ How to Find Bugs

37 class Nothing: def set_value(self, value): self.value = value def print_value(value): print value not_a_thing = Nothing() not_a_thing.set_value(“nowhere”) not_a_thing.print_value() >>> ??? How to Find Bugs