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

DOCX
Lisp programming
PDF
Fourier Series of Music by Robert Fustero
PDF
2Bytesprog2 course_2014_c6_single linked list
PDF
Buzzword poem generator in Python
PPT
PDF
Reg ex cheatsheet
PPT
Learning Algorithms For Life Scientists
PPT
Stacks queues
Lisp programming
Fourier Series of Music by Robert Fustero
2Bytesprog2 course_2014_c6_single linked list
Buzzword poem generator in Python
Reg ex cheatsheet
Learning Algorithms For Life Scientists
Stacks queues

What's hot (14)

PPT
Ch17
PPTX
Periodic pattern mining
PPTX
Merge sort algorithm
PPTX
Python programming for Beginners - II
PDF
Merge sort
PDF
함수형사고 4장 열심히보다는현명하게
PDF
binary search
PDF
Fourier series and transforms
PPTX
Rabin karp string matching algorithm
PPT
Counting sort(Non Comparison Sort)
PDF
Asymptote Curve I
PDF
2015.3.12 the root of lisp
PDF
Writing Perl 6 Rx
PDF
New day 8 examples
Ch17
Periodic pattern mining
Merge sort algorithm
Python programming for Beginners - II
Merge sort
함수형사고 4장 열심히보다는현명하게
binary search
Fourier series and transforms
Rabin karp string matching algorithm
Counting sort(Non Comparison Sort)
Asymptote Curve I
2015.3.12 the root of lisp
Writing Perl 6 Rx
New day 8 examples
Ad

Similar to Programming for engineers in python (20)

PPT
Infix prefix postfix
DOCX
Basic python laboratoty_ PSPP Manual .docx
PPTX
PDF
Pratt Parser in Python
PDF
Free Monads Getting Started
PDF
cel shading as PDF and Python description
PPT
python fundamental for beginner course .ppt
PDF
Go ahead, make my day
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
PDF
Python intro ch_e_comp
PDF
Matlab differential
PDF
datastructure-1 lab manual journals practical
PDF
The Ring programming language version 1.5.4 book - Part 19 of 185
PPTX
Working with functions.pptx. Hb.
PDF
What is Algorithm - An Overview
PDF
Python lambda functions with filter, map & reduce function
PDF
Python for Scientific Computing
PDF
Introduction to functional programming using Ocaml
Infix prefix postfix
Basic python laboratoty_ PSPP Manual .docx
Pratt Parser in Python
Free Monads Getting Started
cel shading as PDF and Python description
python fundamental for beginner course .ppt
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 ...
Python intro ch_e_comp
Matlab differential
datastructure-1 lab manual journals practical
The Ring programming language version 1.5.4 book - Part 19 of 185
Working with functions.pptx. Hb.
What is Algorithm - An Overview
Python lambda functions with filter, map & reduce function
Python for Scientific Computing
Introduction to functional programming using Ocaml
Ad

More from Hoang Nguyen (20)

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

Recently uploaded (20)

PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
KodekX | Application Modernization Development
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Electronic commerce courselecture one. Pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Encapsulation theory and applications.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Modernizing your data center with Dell and AMD
PPTX
A Presentation on Artificial Intelligence
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
KodekX | Application Modernization Development
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
The AUB Centre for AI in Media Proposal.docx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
MYSQL Presentation for SQL database connectivity
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Electronic commerce courselecture one. Pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Encapsulation theory and applications.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Modernizing your data center with Dell and AMD
A Presentation on Artificial Intelligence
Mobile App Security Testing_ A Comprehensive Guide.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Digital-Transformation-Roadmap-for-Companies.pptx

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