SlideShare una empresa de Scribd logo
1 de 14
Recitation 4
Programming for Engineers in Python
Agenda
 Sample problems
 Hash functions & dictionaries (or next week)
 Car simulation
2
A function can be an argument
3
def do_twice(f):
f()
f()
def print_spam():
print 'spam'
>>> do_twice(print_spam)
spam
spam
Fermat’s last theorem
4
 Fermat’s famous theorem claims that for any n>2,
there are no three positive integers a, b, and c
such that:
𝑎 𝑛
+ 𝑏 𝑛
= 𝑐 𝑛
 Let’s check it!
def check_fermat(a,b,c,n):
if n>2 and a**n + b**n == c**n:
print "Fermat was wrong!"
else:
print "No, that doesn't work"
Pierre de Fermat
1601-1665
Fermat’s last theorem
5
>>> check_fermat(3,4,5,2)
No, that doesn't work
>>> check_fermat(3,4,5,3)
No, that doesn't work
 Dirty shortcut since 1995:
def check_fermat(a,b,c,n):
print "Wiles proved it doesn’t work"
Sir Andrew John Wiles
1953-
Cumulative sum
6
 For a given list A we will return a list B such that
B[n] = A[0]+A[1]+…A[n]
 Take 1:
def cumulative_sum(lst):
summ = [ lst[0] ] * len(lst)
for i in range(1, len(lst)):
summ[i] = summ[i-1] + lst[i]
return summ
 Take 2:
def cumulative_sum(lst):
return [sum(lst[0:n]) for n in range(1, len(lst)+1)]
Estimating e by it’s Taylor expansion
7
from math import factorial, e
term = 1
summ = 0
k = 0
while term > 1e-15:
term = 1.0/factorial(k)
summ += term
k += 1
print "Python e:", e
print “Taylor’s e:", summ
print “Iterations:”, k
𝑒 =
𝑘=0
∞
1
𝑘!
= 2 +
1
2
+
1
6
+
1
24
+ ⋯
Brook Taylor,
1685-1731
Estimating π by the Basel
problem
8
from math import factorial, pi, sqrt
term = 1
summ = 0
k = 1
while term > 1e-15:
term = 1.0/k**2
summ += term
k += 1
summ = sqrt(summ*6.0)
print "Python pi:", pi
print “Euler’s pi:", summ
print “Iterations:”, k
𝜋2
6
=
𝑘=1
∞
1
𝑘2 = 1 +
1
4
+
1
9
+
1
16
+ ⋯
Leonard Euler,
1707-1783
Ramanujan’s π estimation (optional)
9
from math import factorial, pi
term = 1
summ = 0
k = 0
while term > 1e-15:
term = factorial(4.0*k) / factorial(k)**4.0
term *= (1103.0+26390.0*k) / 396.0**(4.0*k)
summ += term
k += 1
summ = 1.0/(summ * 2.0*2.0**0.5 / 9801.0)
print "Python Pi:", pi
print "Ramanujan Pi:", summ
print “Iterations:”, k
Srinivasa
Ramanujan,
1887-1920
Triple Double Word
10
 We want to find a word that has three double letters in
it, like aabbcc (which is not a word!)
 Almost qualifiers:
 Committee
 Mississippi
 Write a function to check if a word qualifies
 Write a function that reads a text file and checks all
the words
 Code:
http://www.greenteapress.com/thinkpython/code/carta
lk.py
 Corpus:
http://www.csie.ntu.edu.tw/~pangfeng/Fortran%20exa
mples/words.txt
PyGame
11
 A set of Python modules designed for writing
computer games
 Download & install:
http://pygame.org/ftp/pygame-1.9.2a0.win32-
py2.7.msi
Car game
12
 Control a car moving on the screen
 YouTube demo:
http://www.youtube.com/watch?v=DMOj3HpjemE
 Code: https://gist.github.com/1372753 or in car.py
 Car controlled by
arrows
 Honk with Enter
 Exit with ESC
ToDo List:
13
 Fix stirring problem
 Honk by pressing space
 Car will go from the bottom to top and from one
side to the other (instead of getting stuck)
 Switch to turtle!
2 players car game
14
 Collision avoidance simulator:
 When the cars are too close one of them honks
 Players need to maneuver the cars to avoid honks
 Code: https://gist.github.com/1380291 or cars.py
 Red car controlled by arrows
 Blue car controlled by z, x, c, s

Más contenido relacionado

La actualidad más candente

Python programming for Beginners - II
Python programming for Beginners - IIPython programming for Beginners - II
Python programming for Beginners - IINEEVEE Technologies
 
함수형사고 4장 열심히보다는현명하게
함수형사고 4장 열심히보다는현명하게함수형사고 4장 열심히보다는현명하게
함수형사고 4장 열심히보다는현명하게박 민규
 
Rabin karp string matching algorithm
Rabin karp string matching algorithmRabin karp string matching algorithm
Rabin karp string matching algorithmGajanand Sharma
 
Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)Hossain Md Shakhawat
 
Writing Perl 6 Rx
Writing Perl 6 RxWriting Perl 6 Rx
Writing Perl 6 Rxlichtkind
 

La actualidad más candente (14)

Ch17
Ch17Ch17
Ch17
 
Periodic pattern mining
Periodic pattern miningPeriodic pattern mining
Periodic pattern mining
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
 
Python programming for Beginners - II
Python programming for Beginners - IIPython programming for Beginners - II
Python programming for Beginners - II
 
Merge sort
Merge sortMerge sort
Merge sort
 
함수형사고 4장 열심히보다는현명하게
함수형사고 4장 열심히보다는현명하게함수형사고 4장 열심히보다는현명하게
함수형사고 4장 열심히보다는현명하게
 
binary search
binary searchbinary search
binary search
 
Fourier series and transforms
Fourier series and transformsFourier series and transforms
Fourier series and transforms
 
Rabin karp string matching algorithm
Rabin karp string matching algorithmRabin karp string matching algorithm
Rabin karp string matching algorithm
 
Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)
 
Asymptote Curve I
Asymptote Curve IAsymptote Curve I
Asymptote Curve I
 
2015.3.12 the root of lisp
2015.3.12 the root of lisp2015.3.12 the root of lisp
2015.3.12 the root of lisp
 
Writing Perl 6 Rx
Writing Perl 6 RxWriting Perl 6 Rx
Writing Perl 6 Rx
 
New day 8 examples
New day 8 examplesNew day 8 examples
New day 8 examples
 

Similar a Python Programming Recitation 4: Hash Functions, Dictionaries & Car Simulation

Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfixSelf-Employed
 
Pratt Parser in Python
Pratt Parser in PythonPratt Parser in Python
Pratt Parser in PythonPercolate
 
Free Monads Getting Started
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting StartedKent Ohashi
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Philip Schwarz
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
 
Python intro ch_e_comp
Python intro ch_e_compPython intro ch_e_comp
Python intro ch_e_compPaulo Castro
 
The Ring programming language version 1.5.4 book - Part 19 of 185
The Ring programming language version 1.5.4 book - Part 19 of 185The Ring programming language version 1.5.4 book - Part 19 of 185
The Ring programming language version 1.5.4 book - Part 19 of 185Mahmoud Samir Fayed
 
What is Algorithm - An Overview
What is Algorithm - An OverviewWhat is Algorithm - An Overview
What is Algorithm - An OverviewRamakant Soni
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionARVIND PANDE
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific ComputingAlbert DeFusco
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocamlpramode_ce
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxjovannyflex
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxjovannyflex
 
Subtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff HammondSubtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff HammondPatrick Diehl
 

Similar a Python Programming Recitation 4: Hash Functions, Dictionaries & Car Simulation (20)

Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfix
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
Pratt Parser in Python
Pratt Parser in PythonPratt Parser in Python
Pratt Parser in Python
 
Free Monads Getting Started
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting Started
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
 
Python intro ch_e_comp
Python intro ch_e_compPython intro ch_e_comp
Python intro ch_e_comp
 
Matlab differential
Matlab differentialMatlab differential
Matlab differential
 
Ch2
Ch2Ch2
Ch2
 
The Ring programming language version 1.5.4 book - Part 19 of 185
The Ring programming language version 1.5.4 book - Part 19 of 185The Ring programming language version 1.5.4 book - Part 19 of 185
The Ring programming language version 1.5.4 book - Part 19 of 185
 
What is Algorithm - An Overview
What is Algorithm - An OverviewWhat is Algorithm - An Overview
What is Algorithm - An Overview
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific Computing
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
Mcq cpup
Mcq cpupMcq cpup
Mcq cpup
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptx
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptx
 
Subtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff HammondSubtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff Hammond
 
Ch2 (1).ppt
Ch2 (1).pptCh2 (1).ppt
Ch2 (1).ppt
 

Más de Hoang Nguyen

Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your siteHoang Nguyen
 
How to build a rest api
How to build a rest apiHow to build a rest api
How to build a rest apiHoang Nguyen
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsHoang Nguyen
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksHoang Nguyen
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheHoang Nguyen
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceHoang Nguyen
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friendHoang Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonHoang Nguyen
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonHoang Nguyen
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++Hoang Nguyen
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisHoang Nguyen
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsHoang Nguyen
 
Data abstraction the walls
Data abstraction the wallsData abstraction the walls
Data abstraction the wallsHoang Nguyen
 

Más de Hoang Nguyen (20)

Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 
How to build a rest api
How to build a rest apiHow to build a rest api
How to build a rest api
 
Api crash
Api crashApi crash
Api crash
 
Smm and caching
Smm and cachingSmm and caching
Smm and caching
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Cache recap
Cache recapCache recap
Cache recap
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friend
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python basics
Python basicsPython basics
Python basics
 
Learning python
Learning pythonLearning python
Learning python
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Object model
Object modelObject model
Object model
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Data abstraction the walls
Data abstraction the wallsData abstraction the walls
Data abstraction the walls
 

Último

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 

Último (20)

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 

Python Programming Recitation 4: Hash Functions, Dictionaries & Car Simulation

  • 1. Recitation 4 Programming for Engineers in Python
  • 2. Agenda  Sample problems  Hash functions & dictionaries (or next week)  Car simulation 2
  • 3. A function can be an argument 3 def do_twice(f): f() f() def print_spam(): print 'spam' >>> do_twice(print_spam) spam spam
  • 4. Fermat’s last theorem 4  Fermat’s famous theorem claims that for any n>2, there are no three positive integers a, b, and c such that: 𝑎 𝑛 + 𝑏 𝑛 = 𝑐 𝑛  Let’s check it! def check_fermat(a,b,c,n): if n>2 and a**n + b**n == c**n: print "Fermat was wrong!" else: print "No, that doesn't work" Pierre de Fermat 1601-1665
  • 5. Fermat’s last theorem 5 >>> check_fermat(3,4,5,2) No, that doesn't work >>> check_fermat(3,4,5,3) No, that doesn't work  Dirty shortcut since 1995: def check_fermat(a,b,c,n): print "Wiles proved it doesn’t work" Sir Andrew John Wiles 1953-
  • 6. Cumulative sum 6  For a given list A we will return a list B such that B[n] = A[0]+A[1]+…A[n]  Take 1: def cumulative_sum(lst): summ = [ lst[0] ] * len(lst) for i in range(1, len(lst)): summ[i] = summ[i-1] + lst[i] return summ  Take 2: def cumulative_sum(lst): return [sum(lst[0:n]) for n in range(1, len(lst)+1)]
  • 7. Estimating e by it’s Taylor expansion 7 from math import factorial, e term = 1 summ = 0 k = 0 while term > 1e-15: term = 1.0/factorial(k) summ += term k += 1 print "Python e:", e print “Taylor’s e:", summ print “Iterations:”, k 𝑒 = 𝑘=0 ∞ 1 𝑘! = 2 + 1 2 + 1 6 + 1 24 + ⋯ Brook Taylor, 1685-1731
  • 8. Estimating π by the Basel problem 8 from math import factorial, pi, sqrt term = 1 summ = 0 k = 1 while term > 1e-15: term = 1.0/k**2 summ += term k += 1 summ = sqrt(summ*6.0) print "Python pi:", pi print “Euler’s pi:", summ print “Iterations:”, k 𝜋2 6 = 𝑘=1 ∞ 1 𝑘2 = 1 + 1 4 + 1 9 + 1 16 + ⋯ Leonard Euler, 1707-1783
  • 9. Ramanujan’s π estimation (optional) 9 from math import factorial, pi term = 1 summ = 0 k = 0 while term > 1e-15: term = factorial(4.0*k) / factorial(k)**4.0 term *= (1103.0+26390.0*k) / 396.0**(4.0*k) summ += term k += 1 summ = 1.0/(summ * 2.0*2.0**0.5 / 9801.0) print "Python Pi:", pi print "Ramanujan Pi:", summ print “Iterations:”, k Srinivasa Ramanujan, 1887-1920
  • 10. Triple Double Word 10  We want to find a word that has three double letters in it, like aabbcc (which is not a word!)  Almost qualifiers:  Committee  Mississippi  Write a function to check if a word qualifies  Write a function that reads a text file and checks all the words  Code: http://www.greenteapress.com/thinkpython/code/carta lk.py  Corpus: http://www.csie.ntu.edu.tw/~pangfeng/Fortran%20exa mples/words.txt
  • 11. PyGame 11  A set of Python modules designed for writing computer games  Download & install: http://pygame.org/ftp/pygame-1.9.2a0.win32- py2.7.msi
  • 12. Car game 12  Control a car moving on the screen  YouTube demo: http://www.youtube.com/watch?v=DMOj3HpjemE  Code: https://gist.github.com/1372753 or in car.py  Car controlled by arrows  Honk with Enter  Exit with ESC
  • 13. ToDo List: 13  Fix stirring problem  Honk by pressing space  Car will go from the bottom to top and from one side to the other (instead of getting stuck)  Switch to turtle!
  • 14. 2 players car game 14  Collision avoidance simulator:  When the cars are too close one of them honks  Players need to maneuver the cars to avoid honks  Code: https://gist.github.com/1380291 or cars.py  Red car controlled by arrows  Blue car controlled by z, x, c, s