SlideShare a Scribd company logo
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

More Related Content

What's hot (14)

PPT
Ch17
Abbott
 
PPTX
Periodic pattern mining
Ashis Kumar Chanda
 
PPTX
Merge sort algorithm
Shubham Dwivedi
 
PPTX
Python programming for Beginners - II
NEEVEE Technologies
 
PDF
Merge sort
Abdelrahman Saleh
 
PDF
함수형사고 4장 열심히보다는현명하게
박 민규
 
PDF
binary search
Abdelrahman Saleh
 
PDF
Fourier series and transforms
Pepa Vidosa Serradilla
 
PPTX
Rabin karp string matching algorithm
Gajanand Sharma
 
PPT
Counting sort(Non Comparison Sort)
Hossain Md Shakhawat
 
PDF
Asymptote Curve I
Hirwanto Iwan
 
PDF
2015.3.12 the root of lisp
Chung-Hsiang Ofa Hsueh
 
PDF
Writing Perl 6 Rx
lichtkind
 
PDF
New day 8 examples
jchartiersjsd
 
Ch17
Abbott
 
Periodic pattern mining
Ashis Kumar Chanda
 
Merge sort algorithm
Shubham Dwivedi
 
Python programming for Beginners - II
NEEVEE Technologies
 
Merge sort
Abdelrahman Saleh
 
함수형사고 4장 열심히보다는현명하게
박 민규
 
binary search
Abdelrahman Saleh
 
Fourier series and transforms
Pepa Vidosa Serradilla
 
Rabin karp string matching algorithm
Gajanand Sharma
 
Counting sort(Non Comparison Sort)
Hossain Md Shakhawat
 
Asymptote Curve I
Hirwanto Iwan
 
2015.3.12 the root of lisp
Chung-Hsiang Ofa Hsueh
 
Writing Perl 6 Rx
lichtkind
 
New day 8 examples
jchartiersjsd
 

Similar to Programming for engineers in python (20)

DOCX
python.docx
palaniyappan6
 
PDF
Looping
MuhammadBakri13
 
DOCX
cs class 12 project computer science .docx
AryanSheoran1
 
DOCX
Basic python laboratoty_ PSPP Manual .docx
Kirubaburi R
 
PDF
Week3
준성 조
 
PDF
Galios: Python Programming
Kishoj Bajracharya
 
PDF
python lab programs.pdf
CBJWorld
 
PDF
PyLecture4 -Python Basics2-
Yoshiki Satotani
 
PDF
Introduction to Recursion (Python)
Thai Pangsakulyanont
 
PDF
Mementopython3 english
yassminkhaldi1
 
PDF
Introduction to python cheat sheet for all
shwetakushwaha45
 
PDF
Mementopython3 english
ssuser442080
 
PDF
Python3
Sourodip Kundu
 
PDF
A Taste of Python - Devdays Toronto 2009
Jordan Baker
 
PDF
Python Programming
Sreedhar Chowdam
 
PDF
Python Lab manual program for BE First semester (all department
Nazeer Wahab
 
PDF
Python3 cheatsheet
Gil Cohen
 
DOCX
python file for easy way practicle programs
vineetdhand2004
 
PDF
Course project solutions 2019
Robert Geofroy
 
PPT
2010 3-24 cryptography stamatiou
vafopoulos
 
python.docx
palaniyappan6
 
cs class 12 project computer science .docx
AryanSheoran1
 
Basic python laboratoty_ PSPP Manual .docx
Kirubaburi R
 
Week3
준성 조
 
Galios: Python Programming
Kishoj Bajracharya
 
python lab programs.pdf
CBJWorld
 
PyLecture4 -Python Basics2-
Yoshiki Satotani
 
Introduction to Recursion (Python)
Thai Pangsakulyanont
 
Mementopython3 english
yassminkhaldi1
 
Introduction to python cheat sheet for all
shwetakushwaha45
 
Mementopython3 english
ssuser442080
 
A Taste of Python - Devdays Toronto 2009
Jordan Baker
 
Python Programming
Sreedhar Chowdam
 
Python Lab manual program for BE First semester (all department
Nazeer Wahab
 
Python3 cheatsheet
Gil Cohen
 
python file for easy way practicle programs
vineetdhand2004
 
Course project solutions 2019
Robert Geofroy
 
2010 3-24 cryptography stamatiou
vafopoulos
 
Ad

More from Hoang Nguyen (20)

PPTX
Rest api to integrate with your site
Hoang Nguyen
 
PPTX
How to build a rest api
Hoang Nguyen
 
PPTX
Api crash
Hoang Nguyen
 
PPTX
Smm and caching
Hoang Nguyen
 
PPTX
Optimizing shared caches in chip multiprocessors
Hoang Nguyen
 
PPTX
How analysis services caching works
Hoang Nguyen
 
PPTX
Hardware managed cache
Hoang Nguyen
 
PPTX
Directory based cache coherence
Hoang Nguyen
 
PPTX
Cache recap
Hoang Nguyen
 
PPTX
Python your new best friend
Hoang Nguyen
 
PPTX
Python language data types
Hoang Nguyen
 
PPTX
Python basics
Hoang Nguyen
 
PPTX
Learning python
Hoang Nguyen
 
PPTX
Extending burp with python
Hoang Nguyen
 
PPTX
Cobol, lisp, and python
Hoang Nguyen
 
PPT
Object oriented programming using c++
Hoang Nguyen
 
PPTX
Object oriented analysis
Hoang Nguyen
 
PPTX
Object model
Hoang Nguyen
 
PPTX
Data structures and algorithms
Hoang Nguyen
 
PPT
Data abstraction the walls
Hoang Nguyen
 
Rest api to integrate with your site
Hoang Nguyen
 
How to build a rest api
Hoang Nguyen
 
Api crash
Hoang Nguyen
 
Smm and caching
Hoang Nguyen
 
Optimizing shared caches in chip multiprocessors
Hoang Nguyen
 
How analysis services caching works
Hoang Nguyen
 
Hardware managed cache
Hoang Nguyen
 
Directory based cache coherence
Hoang Nguyen
 
Cache recap
Hoang Nguyen
 
Python your new best friend
Hoang Nguyen
 
Python language data types
Hoang Nguyen
 
Python basics
Hoang Nguyen
 
Learning python
Hoang Nguyen
 
Extending burp with python
Hoang Nguyen
 
Cobol, lisp, and python
Hoang Nguyen
 
Object oriented programming using c++
Hoang Nguyen
 
Object oriented analysis
Hoang Nguyen
 
Object model
Hoang Nguyen
 
Data structures and algorithms
Hoang Nguyen
 
Data abstraction the walls
Hoang Nguyen
 
Ad

Recently uploaded (20)

PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Learn Computer Forensics, Second Edition
AnuraShantha7
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Learn Computer Forensics, Second Edition
AnuraShantha7
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 

Programming for engineers in python

  • 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