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)

PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 

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