Python Programming, 1/e 1



Similar documents
for while ' while ' for * for <var> in <sequence>: <body> $ %%" 0 *0

CS177 MIDTERM 2 PRACTICE EXAM SOLUTION. Name: Student ID:

Simple, not Simplistic Squeezing the most from CS1. Python! John M. Zelle, Ph.D. Wartburg College

Lecture 2, Introduction to Python. Python Programming Language

Chapter 3 Writing Simple Programs. What Is Programming? Internet. Witin the web server we set lots and lots of requests which we need to respond to

Python Lists and Loops

Exercise 1: Python Language Basics

Python Programming: An Introduction to Computer Science

Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++)

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Chapter 2 Writing Simple Programs

PYTHON Basics

Computer Science 217

Introduction to: Computers & Programming: Input and Output (IO)

ESCI 386 Scientific Programming, Analysis and Visualization with Python. Lesson 5 Program Control

Building a Python Plugin

Crash Dive into Python

Exercise 4 Learning Python language fundamentals

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

13.0 Central Limit Theorem

Programming Exercises

To understand the concept of objects and how they can be used to simplify programs.

Self-review 9.3 What is PyUnit? PyUnit is the unit testing framework that comes as standard issue with the Python system.

CONCEPT-II. Overview of demo examples

A skip list container class in Python

Hadoop and Map-reduce computing

Below is a very brief tutorial on the basic capabilities of Excel. Refer to the Excel help files for more information.

Crash Dive into Python

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

IBM SPSS Statistics 20 Part 1: Descriptive Statistics

Chapter 4 State Machines

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output

Introduction to Python

Python Evaluation Rules

Android Based Appointment Scheduler and Location Helper using file operation

Introduction to Python

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

How do I share a file with a friend or trusted associate?

CSC 221: Computer Programming I. Fall 2011

NLP Programming Tutorial 0 - Programming Basics

CRASH COURSE PYTHON. Het begint met een idee

Engineering Problem Solving and Excel. EGN 1006 Introduction to Engineering

Scatter Plots with Error Bars

Informatica e Sistemi in Tempo Reale

PHP Tutorial From beginner to master

Python for Rookies. Example Examination Paper

Python Programming: An Introduction To Computer Science

PIC 10A. Lecture 7: Graphics II and intro to the if statement

4 Other useful features on the course web page. 5 Accessing SAS

Reporting Manual. Prepared by. NUIT Support Center Northwestern University

AMS 5 CHANCE VARIABILITY

Data exploration with Microsoft Excel: analysing more than one variable

Graphics Module Reference

Python Loops and String Manipulation

How To Use Optionbot 2.0 On A Pc Or Mac Or Mac (For Pc) Or Mac) Or Pc (For Mac)

Advanced Programming with LEGO NXT MindStorms

Doing Multiple Regression with SPSS. In this case, we are interested in the Analyze options so we choose that menu. If gives us a number of choices:

Grinder Webtest Documentation

G563 Quantitative Paleontology. SQL databases. An introduction. Department of Geological Sciences Indiana University. (c) 2012, P.

Data representation and analysis in Excel

Appendix K Introduction to Microsoft Visual C++ 6.0

Using Files as Input/Output in Java 5.0 Applications

I.T. Services. Quick Start Guide. E mail at Hope

BUSINESS DATA ANALYSIS WITH PIVOTTABLES

UPS System Capacity Management Configuration Utility

First Bytes Programming Lab 2

2 SYSTEM DESCRIPTION TECHNIQUES

ESPResSo Summer School 2012

Section VIII: ACH Payment Processing

Algorithm Design and Recursion

Sorting. Lists have a sort method Strings are sorted alphabetically, except... Uppercase is sorted before lowercase (yes, strange)

SECTION 2-1: OVERVIEW SECTION 2-2: FREQUENCY DISTRIBUTIONS

4. Descriptive Statistics: Measures of Variability and Central Tendency

Python Classes and Objects

NextGen EHR: Clinic Password and User Preferences Setup in PROD

CSC 180 H1F Algorithm Runtime Analysis Lecture Notes Fall 2015

Appendix III: SPSS Preliminary

Software Tool Seminar WS Taming the Snake

Python Programming: An Introduction to Computer Science

Solutions to Homework 6

CS 100 Introduction to Computer Science Lab 1 - Playing with Python Due September 21/23, 11:55 PM

Frequently Asked Questions

DS-0321 FFT Analysis Software Operation manual Basic operation procedure for Configuration Setting

Programming Languages CIS 443

Homework 4 Statistics W4240: Data Mining Columbia University Due Tuesday, October 29 in Class

15. Functions and Lists. Example 2: Sorting a List of Numbers. Example 1: Computing the Diameter of a Cloud of Points

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

Instruction Set Architecture of Mamba, a New Virtual Machine for Python

Sage Timesheet Web Access How To Use Timesheet

Using Excel for Statistical Analysis

Basic C Shell. helpdesk@stat.rice.edu. 11th August 2003

Homework 2. A 4*4 image with 16 pixels Borders unaltered. Color of B2 = Average color of (B1,A2,B3,C2) A1 A2 A3 A4 B1 B2 B3 B4 C1 C2 C3 C4 D1 D2 D3 D4

InfiniteInsight 6.5 sp4

8. MACROS, Modules, and Mouse

Bill Burton Albert Einstein College of Medicine April 28, 2014 EERS: Managing the Tension Between Rigor and Resources 1

Transcription:

"$% " " " ) " * -. ) / 0 ( + 34 average4.py A program to average a set of numbers Illustrates sentinel loop using empty string as sentinel def main(): sum = 0.0 count = 0 xstr = raw_input("enter a number (<Enter> to quit) >> ") while xstr = "": x = eval(xstr) sum = sum + x count = count + 1 xstr = raw_input("enter a number (<Enter> to quit) >> ") print "\nthe average of the numbers is", sum / count main() 1 " * 300 6 0 ) 5 Python Programming, 1/e 1

" *89 :+5;( 5 5 " "0 )) 7 4 " ( x x ) s = i n 1 < x xi ")* ( x x ) i => ; " *=> +5; ( "54 " ( 6.8 ) + ( 6.8 4) + ( 6.8 6) + ( 6.8 9) + ( 6.8 13) = 149.6 149.6 s = = 37.4 = 6.11 5 1? * $3 % @...3 30.A Python Programming, 1/e

* :* B? ( C 8 * 9 * n 1 i i= 0 ( s * s. *0 sum = 0 for i in range(n): sum = sum + s[i] *0 + * * $s% ) $ s[i]% )9 " 0 * 1 5 E*FKE*F E*FJE8)F E*FGH $E*F% E*FGH EFE*F E)FE*F - I ) -$% 0 3 " * >>> lst = [1,,3,4] >>> 3 in lst True 7 4 Python Programming, 1/e 3

" ) 0 sum = 0 for x in s: sum = sum + x L0 >>> lst = [1,,3,4] >>> lst[3] 4 >>> lst[3] = "Hello >>> lst [1,, 3, Hello] >>> lst[] = 7 >>> lst [1,, 7, Hello] " 1? 9 zeroes = [0] * 50 ;? nums = [] x = input(enter a number: ) while x >= 0: nums.append(x) x = input(enter a number: ) <nums 0 - EF$)% EF$% EF$% EF)$)% EF$)% EF$)% EF$)% EF$% - ) $% I I)) )) I) ) >>> lst = [3, 1, 4, 1, 5, 9] >>> lst.append() >>> lst [3, 1, 4, 1, 5, 9, ] >>> lst.sort() >>> lst [1, 1,, 3, 4, 5, 9] >>> lst.reverse() >>> lst [9, 5, 4, 3,, 1, 1] >>> lst.index(4) >>> lst.insert(4, "Hello") >>> lst [9, 5, 4, 3, Hello,, 1, 1] >>> lst.count(1)s >>> lst.remove(1) >>> lst [9, 5, 4, 3, Hello,, 1] >>> lst.pop(3) 3 >>> lst [9, 5, 4, Hello,, 1] ( -3 6 0 del + Python Programming, 1/e 4

>>> mylist=[34, 6, 0, 10] >>> del mylist[1] >>> mylist [34, 0, 10] >>> del mylist[1:3] >>> mylist [34] del 38 * ) M 1 5 * 0. 0 3 7 4 3 getnumbers.3 " def getnumbers(): nums = [] start with an empty list sentinel loop to get numbers xstr = raw_input("enter a number (<Enter> to quit) >> ") while xstr = "": x = eval(xstr) nums.append(x) add this value to the list xstr = raw_input("enter a number (<Enter> to quit) >> ") return nums L data = getnumbers() ; (? Python Programming, 1/e 5

N def mean(nums): sum = 0.0 for num in nums: sum = sum + num return sum / len(nums) ")0 0 stdeva stdeva ( ( I stdev 3 stdev def stdev(nums, xbar): sumevsq = 0.0 for num in nums: dev = xbar - num sumevsq = sumevsq + dev * dev return sqrt(sumevsq/(len(nums)-1)) " sumevsq * (( (+.3.3 0 : 8 9 B B (1 (5 Python Programming, 1/e 6

def median(nums): nums.sort() size = len(nums) midpos = size / if size % == 0: median = (nums[midpos] + nums[midpos-1]) /.0 else: median = nums[midpos] return median. @ def main(): print This program computes mean, median and standard deviation. data = getnumbers() xbar = mean(data) std = stdev(data, xbar) med = median(data) print \nthe mean is, xbar print The standard deviation is, std print The median is, med (7 (4 3 if name == main : main() )30 0. )0 (; +? / 0 8 3 / Sutdent Get the name of the input file from the user Read student information into a list Sort the list by GPA Get the name of the output file from the user Write the student information from the list into a file / + + Python Programming, 1/e 7

3 " def readstudents(filename): infile = open(filename, r) students = [] for line in infile: students.append(makestudent(line)) infile.close() return students.3 makestudentgpa 3 3 0, * def writestudents(students, filename): students is a list of Student objects outfile = open(filename, w) for s in students: outfile.write("%s\t%f\t%f\n" % (s.getname(),s.gethours(),s.getqpoints())) outfile.close() +( ++ L readstudents writestudents 0 / sort < A 8cmp cmp 0-1 0 3*1 +1 +5 >>> cmp(1-1 >>> cmp(,1) 1 >>> cmp("a","b") -1 >>> cmp(1,1.0) 0 >>> cmp("a",5) 1 :3 0= > "0 0 sort. cmp8 0 sort "/ 0-101 +7 +4 Python Programming, 1/e 8

.8cmp def cmpgpa(s1, s): return cmp(s1.gpa(), s.gpa(). $cmpgpa% data.sort(cmpgpa) data.sort(cmpgpa) N3()3 cmpgpa "3 cmpgpa cmpgpa +; 1? O O / 0 $% B$PP% BGH $0$%% $% $% UUUUBBPUUUUP B$PP% $% $QRSRSRSQR $ N$% <$% T$%%% $% /$% $ $% $%% $% Q" /Q BU$Q, Q% B$% $/% BU$Q, Q% $% Q"Q dieview 00 00pip1 pippip3c 1 1. A 0 self.pip1 = self. makepip(cx, cy) makepip ieview pips = [] pips.append(self. makepip(cx-offset,cy-offset) pips.append(self. makepip(cx-offset,cy) self.pips = pips 1( 1+ Python Programming, 1/e 9

self.pips = [self. makepip(cx-offset,cy-offset), self. makepip(cx-offset,cy), self. makepip(cx+offset,cy+offset) ] 0 VH3 00 11 0 "0 0 for pip in self.pips: pip.setfill(self.background) " @ 15.0 00 self.pip1.setfill(self.foreground) self.pip4.setfill(self.foreground) self.pip7.setfill(self.foreground) self.pips[0].setfill(self.foreground) self.pips[3].setfill(self.foreground) self.pips[6].setfill(self.foreground) <3 for i in [0,3,6]: self.pips[i].setfill(self.foreground).0 0 @ Loop through pips and turn them all off etermine the list of pip indexes to turn on Loop through the list of indexes - turn on those pips 17 14 for pip in self.pips: self.pip.setfill(self.background) if value == 1: on = [3] elif value == : on = [0,6] elif value == 3: on = [0,3,6] elif value == 4: on = [0,,4,6] elif value == 5: on = [0,,3,4,6] else: on = [0,1,,3,4,5,6] for i in on: self.pips[i].setfill(self.foreground).@ " value.08. ) :)( [0,3,6] ( 1; 5? Python Programming, 1/e 10

<38 ontable = [ [], [3], [,4], [,3,4], [0,,4,6], [0,,3,4,6], [0,1,,4,5,6] ] for pip in self.pips: self.pip.setfill(self.background) on = ontable[value] for i in on: self.pips[i].setfill(self.foreground) ontable = [ [], [3], [,4], [,3,4], [0,,4,6], [0,,3,4,6], [0,1,,4,5,6] ] for pip in self.pips: self.pip.setfill(self.background) on = ontable[value] for i in on: self.pips[i].setfill(self.foreground) "VGH3? 3 "ontable dieview0 5 5 dieview.py A widget for displaying the value of a die. This version uses lists to simplify keeping track of pips. class ieview: """ ieview is a widget that displays a graphical representation of a standard six-sided die.""" def init (self, win, center, size): """Create a view of a die, e.g.: d1 = Gie(myWin, Point(40,50), 0) creates a die centered at (40,50) having sides of length 0.""" first define some standard values self.win = win self.background = "white" color of die face self.foreground = "black" color of the pips self.psize = 0.1 * size radius of each pip hsize = size /.0 half of size offset = 0.6 * hsize distance from center to outer pips create a square for the face cx, cy = center.getx(), center.gety() p1 = Point(cx-hsize, cy-hsize) p = Point(cx+hsize, cy+hsize) rect = Rectangle(p1,p) rect.draw(win) rect.setfill(self.background) Create 7 circles for standard pip locations self.pips = [ self. makepip(cx-offset, cy-offset), self. makepip(cx-offset, cy), self. makepip(cx-offset, cy+offset), self. makepip(cx, cy), self. makepip(cx+offset, cy-offset), self. makepip(cx+offset, cy), self. makepip(cx+offset, cy+offset) ] Create a table for which pips are on for each value self.ontable = [ [], [3], [,4], [,3,4], [0,,4,6], [0,,3,4,6], [0,1,,4,5,6] ] self.setvalue(1) def makepip(self, x, y): """Internal helper method to draw a pip at (x,y)""" pip = Circle(Point(x,y), self.psize) pip.setfill(self.background) pip.setoutline(self.background) pip.draw(self.win) return pip def setvalue(self, value): """ Set this die to display value.""" Turn all the pips off for pip in self.pips: pip.setfill(self.background) Turn the appropriate pips back on for i in self.ontable[value]: self.pips[i].setfill(self.foreground) ). dieview. @, ) = > 5( 5+ "dieview ontable. $ % 3 " $?8;% $% :$K8J% 0 V3 VE83 0 VB3 51 55 Python Programming, 1/e 11

.0 B. 57 54 : " def init (self): create the window for the calculator win = GraphWin("calculator") win.setcoords(0,0,6,7) win.setbackground("slategray") self.win = win ) create list of buttons start with all the standard sized buttons bspecs gives center coords and label of buttons bspecs = [(,1,0), (3,1,.), (1,,1), (,, (3,,3), (4,,+), (5,,-), (1,3,4), (,3,5), (3,3,6), (4,3,*), (5,3,/), (1,4,7), (,4,8), (3,4,9), (4,4,<-),(5,4,C)] self.buttons = [] for cx,cy,label in bspecs: self.buttons.append(button(self.win,point(cx,cy),.75,.75,label)) create the larger = button self.buttons.append(button(self.win, Point(4.5,1), 1.75,.75, "=")) activate all buttons for b in self.buttons: b.activate() bspecs 5; 7?, 00V$%3 VGH3 " * (cx,cy,label)=<next item from bspecs>,bspecs. 0 " 3 cx,cy,label =,1, 0 7 7 Python Programming, 1/e 1

, bspecs 0 " Button 6 3 ). ) <3 bg = Rectangle(Point(.5,5.5), Point(5.5,6.5)) bg.setfill(white) bg.draw(self.win) text = Text(Point(3,6), "") text.draw(self.win) text.setface("courier") text.setstyle("bold") text.setsize(16) self.display = text 7( 7+ N.3 0 def run(self): Infinite event loop to process button clicks. while True: key = self.getbutton() self.processbutton(key). 0 0 " 0 0 def getbutton(self): Waits for a button to be clicked and returns the label of the button that was clicked. while True: p = self.win.getmouse() for b in self.buttons: if b.clicked(p): return b.getlabel() method exit 71 75 < 0 for 0 0p ) " 0 key text self.display.settext(text+key) 77 74 Python Programming, 1/e 13

"00 self.display.settext( ) "00 self.display.settext(text[:-1]) "*0) try: result = eval(text) except: result = ERROR self.display.settext(str(result)) 8) 3 ) 3 ERROR 7; 4? N8* 8 N " * 0 ) 4 4 " 008.$ %0 $% 3008 0 0 4( 4+ Python Programming, 1/e 14

08 >>> passwd = {"guido":"superprogrammer", "turing":"genius", "bill":"monopoly"} W V3 "0 0 ) >>> passwd["guido"] superprogrammer >>> passwd["bill"] monopoly <dictionary>[<key>] 0 41 45 " 0 >>> passwd["bill"] = "bluescreen >>> passwd {turing: genius, bill: bluescreen, guido: superprogrammer} 3 A - 000 0 *@ 47 44 0 W 8 8 )$ % >>> passwd[newuser] = "ImANewbie >>> passwd {turing: genius, bill: bluescreen, newuser: ImANewbie, guido: superprogrammer} 4; ;? Python Programming, 1/e 15

08 passwords passwd = {} for line in open(passwords, r): user, pass = string.split(line) passwd[user] = pass ; ; - <dict>.has_key(<key>) <key> in <dict> <dict>.keys() <dict>.values() <dict>.items() <dict>.get(<key>, <default>) del <dict> [<key>] <dict>.clear() - I 0 has_key I0 I I(key, value) 08 keym default ;( >>> passwd.keys() [turing, bill, newuser, guido] >>> passwd.values() [genius, bluescreen, ImANewbie, superprogrammer] >>> passwd.items() [(turing, genius), (bill, bluescreen), (newuser, ImANewbie), (guido, superprogrammer)] >>> passwd.has_key(bill) True >>> fred in passwd False >>> passwd.get(bill, unknown) bluescreen >>> passwd.get(john, unknown) unknown >>> passwd.clear() >>> passwd {} ;+ N 9) " ) $0 % 8..3 @ ;1 ;5 Python Programming, 1/e 16

.0 3 counts "w counts[w] = counts[w] + 1 "3" 3 counts 8 )08 KeyError if w is already in counts: add one to the count for w else: set count for w to 1 ;7 ;4 " if counts.has_key(w): counts[w] = counts[w] + 1 else: counts[w] = 1 counts[w] = counts.get(w,0) + 1 w get? w ;;?? "0) *. ) $0 => => % $ =@> =>% fname = raw_input("file to analyze: ") read file as one long string text = open(fname, r).read() convert all letters to lower case text = string.lower(text) replace each punctuation character with a space for ch in "$%()*+,-./:;<=>?@[\\]^_{ }~: text = string.replace(text, ch, ) split string at whitespace to form a list of words words = string.split(text) Now we can easily loop through the words to build the counts dictionary?? Python Programming, 1/e 17

. counts = {} for w in words: counts[w] = counts.get(w, 0) + 1. 9counts. <A get list of words that appear in document uniquewords = counts.keys() put list of words in alphabetical order uniquewords.sort() print words and associated counts for w in uniquewords: print w, counts[w] " 0?(?+. " 90 ". 08 items items = counts.items() [(foo,5), (bar,7), (spam,376),...] items.sort 8 @.3 @?1?5. 0$08 %8? def compareitems((w1, c1), (w, c)): if c1 > c: return -1 elif c1 == c: return cmp(w1, w) else: return 1 def compareitems((w1, c1), (w, c)): if c1 > c: return -1 elif c1 == c: return cmp(w1, w) else: return 1 "0 8-1?7?4 Python Programming, 1/e 18

def compareitems((w1, c1), (w, c)): if c1 > c: return -1 elif c1 == c: return cmp(w1, w) else: return 1 *0 3 " def compareitems((w1, c1), (w, c)): if c1 > c: return -1 elif c1 == c: return cmp(w1, w) else: return 1 1 " items.sort(compareitems)?;? " for i in range(n): print "%-10s%5d" % items[i] N 8? : 8 1 N 3 =>GH wordfreq.py Program to analyze the frequency of words in a text file. Illustrates Python dictionaries import string def compareitems((w1,c1), (w,c)): if c1 > c: return -1 elif c1 == c: return cmp(w1, w) else: return 1 def main(): print "This program analyzes word frequency in a file" print "and prints a report on the n most frequent words.\n" get the sequence of words from the file fname = raw_input("file to analyze: ") text = open(fname,r).read() text = string.lower(text) for ch in "$%\()*+,-./:;<=>?@[\\]^_`{ }~: text = string.replace(text, ch, ) words = string.split(text) construct a dictionary of word counts counts = {} for w in words: counts[w] = counts.get(w,0) + 1 output analysis of n most frequent words. n = input("output analysis of how many words? ") items = counts.items() items.sort(compareitems) for i in range(n): print "%-10s%5d" % items[i] ( Python Programming, 1/e 19