Recitation 5 Programming for Engineers in Python.

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

Lecture 04 – Classes.  Python has a number of classes built-in  lists, dictionaries, sets, int, float, boolean, strings  We can define our own classes.
CIT 590 Intro to Programming Classes. Schedule change The upcoming HW (HW6) is your last major Python HW. It will involve object oriented programming.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
References: 1. “Programming in LUA, 2 nd ed.”, Roberto Lerusalmschy Chapters (primarily) 2. “Lua Reference Manual” (included in Lua installation.
Dictionaries: Keeping track of pairs
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 9 Classes.
Lilian Blot TOWARDS MORE ADVANCED CONCEPTS & OBJECT ORIENTED PROGRAMMING Building Data Structure Autumn 2014 TPOP 1.
Object Oriented Design and Classes
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
CIS-5301 Introduction to Python Edward Loper. CIS-5302 Outline Data –strings, variables, lists, dictionaries Control Flow Working with files Modules Functions.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
INFO 206 Lab Exercise 1 Introduction to Classes and Objects 1/18/2012i206 Lab 1 - Exercise1.
Object Oriented Design and Classes. What is a class? Programming mechanism to support OOD Data and the methods that operate on that data – collectively.
Computer Science 111 Fundamentals of Programming I Introduction to Programmer-Defined Classes.
Recitation 1 Programming for Engineers in Python.
 1 String and Data Processing. Sequential Processing Processing each element in a sequence for e in [1,2,3,4]: print e for c in “hello”: print c for.
January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
CIT 590 Intro to Programming Style Classes. Remember to finish up findAllCISCourses.py.
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
CS 202, Spring 2003 Fundamental Structures of Computer Science II Bilkent University1 Hashing CS 202 – Fundamental Structures of Computer Science II Bilkent.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
60 Questions (review for final exam) CSC 161: The Art of Programming Prof. Henry Kautz 12/7/
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Classes 1 COMPSCI 105 S Principles of Computer Science.
Built-in Data Structures in Python An Introduction.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
CLASSES Python Workshop. Introduction  Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax.
Google App Engine MemCache ae-09-session
P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that.
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
PYTHON OBJECTS & CLASSES. What is an object? The abstract idea of anything What is in an object: Attributes Characteristics Represented by internal variables.
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
Object Oriented Programing (OOP)
Loops Robin Burke IT 130. Outline Announcement: Homework #6 Conditionals (review) Iteration while loop while with counter for loops.
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
Compsci 101.2, Fall Plan for October 29 l Review dictionaries and their use  Very efficient, easy to use  Efficiency doesn't matter much for.
Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
OOP Basics Classes & Methods (c) IDMS/SQL News
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
Dr. Philip Cannata 1 Python Overview. Dr. Philip Cannata 2 “Bad program” developed during class # The following python statement has python variables.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
CSC 231: Introduction to Data Structures Python and Objects – Day 3 Dr. Curry Guinn.
More Python Data Structures  Classes ◦ Should have learned in Simpson’s OOP ◦ If not, read chapters in Downey’s Think Python: Think like a Computer Scientist.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
CSC 222: Object-Oriented Programming
CSC 222: Object-Oriented Programming
George Mason University
Topics Procedural and Object-Oriented Programming Classes
CSC 131: Introduction to Computer Science
Object Oriented Programming
Data Abstraction UW CSE 160 Spring 2018.
Adapted from slides by Marty Stepp and Stuart Reges
Python dicts and sets Some material adapted from Upenn cis391 slides and other sources.
Fundamentals of Programming I Commonly Used Methods More Modeling
(more) Python.
CSE 231 Lab 11.
Lecture 18 Python OOP.
A Level Computer Science Topic 6: Introducing OOP
Hash Maps Implementation and Applications
CSE 231 Lab 8.
Dictionary.
Data Abstraction UW CSE 160.
Presentation transcript:

Recitation 5 Programming for Engineers in Python

Agenda Birthday problem Hash functions & dictionaries Frequency counter Object Oriented Programming 2

Random Birthday Problem 3 What are the odds that two people will have the same birthday? (1/365~0.27%) In a room with 23 people what are the odds that at least two will have the same birthday? (~50%) In a room with n people, what are the odds? y See “Think Python” book for problems and solutions!Think Python

Notes on birthday problem 4 >>> s = t[:] Creates a copy of t in s – changing t will not change s! >>> random.randint(a, b) Returns an integer between a and b, inclusive

Hash functions 5 Gets a BIG value and returns a SMALL value Consistent: if x==y then hash(x)==hash(y) Collisions: there are some x!=y such that hash(x)==hash(y)

Hash functions 6 >>> hash("yoav") >>> hash(“noga") >>> hash(1) 1 >>> hash(“1")

Dictionary “implementation” 7 >>> dic = {“yoav” : “ram”, “noga” : “levy”} >>> dic[“yoav”] ‘ram’ What happens under the hood (roughly): >>> hashtable = [] >>> hashtable[hash(“yoav”)]=“ram” >>> hashtable[hash(“noga”)]=“levy” >>> hashtable[hash(“yoav”)] ‘ram’ For a detailed explanation:

Why must dictionary keys be immutable? 8 key= [1,2,3] ‘shakshuka’ hash(key)= 5863 hash(…) We want this mapping Implemented by this mapping

Why must dictionary keys be immutable? 9 key= [1000,2,3] ‘shakshuka’ hash(key)= 5863 hash(…) We want this mapping hash(key)= 9986 We change an entry in the key: >>> key[0]=1000 But it doesn’t change the mapping! Now, key doesn’t map to the value! This is the mapping we have

Why must dictionary keys be immutable? 10 Consider using a list as a key (this is NOT a real Python code!) >>> key = [1,2,3] >>> hash(key) # assuming key was hashable – it is not! 2011 >>> dic = {key : “shakshuka”} # hashtable[2011] = “shakshuka” >>> key[0] = 1000 >>> hash(key) 9986 >>> dic[key] # hashtable[1983] Traceback (most recent call last): File " ", line 1, in dic[key] KeyError: ‘[1000,2,3]‘ The key [1000,2,3] doesn’t exist!

Frequency Counter  Substitution cyphers are broken by frequency analysis  So we need to learn the frequencies of English letters  We find a long text and start counting  Which data structure will we use? s u p e r c a l i f r a g i l i s t i c e x p i a l i d o c i o u s 11

Frequency Counter str1 = 'supercalifragilisticexpialidocious‘ # count letters charCount = {} for char in str1: charCount[char] = charCount.get(char, 0) + 1 # sort alphabetically sortedCharTuples = sorted(charCount.items()) 12 Returned if char is not in the dictionary

Frequency Counter # print for charTuple in sortedCharTuples: print charTuple[0], ‘ = ‘, charTuple[1] a = 3 c = 3 d = 1 e = 2 f = 1 g = 1 … 13

The Table Does Not Lie 14 We will construct a dictionary that holds the current table of the basketball league and a function that changes the table based on this week results Initialize the table: >>> table = {} >>> for team in team_list: table[team] = 0 >>> table {'jerusalem': 0, ‘tel-aviv': 0, 'ashdod': 0, …}

Changing the table 15 League results is a list of tuples - (winner, loser): >>> results= [(“galil”,”tel-aviv”),( “herzelia”,”ashdod”),…] We define a function to update the league table: def update_table(results): for winner,loser in results: table[winner] = table[winner]+2 table[loser] = table[loser]+1

Comparing teams 16 The table must be sorted by points, we need a compare function: def cmp_teams(team1, team2): pointCmp = cmp(team1[1],team2[1]) if pointCmp != 0: return pointCmp else: return -cmp(team1[0],team2[0]) >>> cmp_teams(('galil', 2),('ashdod', 1)) 1 >>> cmp_teams(('galil', 2),('ashdod', 2)) >>> cmp_teams(('galil',2),('tel-aviv', 2)) 1

Showing the table 17 The table must be sorted by points, in descending order: >>> s_teams = sorted(table.items(),cmp_teams,reverse=True) >>> for team, points in s_teams: print points,"|",team.capitalize() 2 | Galil 2 | Herzelia 2 | Jerusalem 1 | Ashdod 1 | Tel-aviv

Object Oriented Programing 18 Started in class – more next week Model human thinking We perceive the world as objects and relations Encapsulation Keep data and relevant functions together Modularity Replace one part without changing the others Reusability Use the same code for different programs Inheritance Extend a piece of code without changing it

Objects 19

Classes 20 Definition class ClassName (object): statement1 statement2... Initialization >>> foo = Foo() >>> foo # this is an instance of class Foo >>> type(foo)

__init__ - the constructor 21 __init__ is used to initialize an instance Can have arguments other than self class Student(): def __init__(self,name): self.name = name >>> student = Student(‘Yossi') >>> student.name ‘Yossi'

self 22 self is a reference to the instance itself Used to refer to the data and methods The first argument of a method is always self, but there’s no need to give it to the method

self – cont. 23 class ClassExample(): def get_self(self): return self >>> example = ClassExample() >>> example >>> example.get_self() >>> ClassExample.get_self(example ) >>> ClassExample.get_self() Traceback (most recent call last): File " ", line 1, in ClassExample.get_self() TypeError: unbound method get_self() must be called with ClassExample instance as first argument (got nothing instead)

Example – Bank Account 24 Code: class BankAccount(object): def __init__(self, initial_balance=0): self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount def is_overdrawn(self): return self.balance < 0 >>> my_account = BankAccount(15) >>> my_account.withdraw(5) >>> my_account.deposit(3) >>> print “Balance:”,my_account.balance,”, Overdraw:”,my_account.is_overdrawn() Balance: 13, Overdraw: False

Multimap 25 A dictionary with more than one value for each key We already needed it once or twice and used: >>> lst = d.get(key, []) >>> lst.append(value) >>> d[key] = lst Now we create a new data type

Multimap 26 Use case – a dictionary of countries and their cities: >>> m = Multimap() >>> m.put('Israel','Tel-Aviv') >>> m.put('Israel','Jerusalem') >>> m.put('France','Paris') >>> m.put_all('England',('London','Manchester','Moscow')) >>> m.remove('England','Moscow') >>> print m.get('Israel') ['Tel-Aviv', 'Jerusalem'] Code:

Advanced example: HTTP Server 27 We will write a simple HTTP server The server allows to browse the file system through the browser Less than 20 lines, including imports! Code: Another one - this one writes the time and the server’s IP address: