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

More Related Content

What's hot

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
 

What's hot (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 to Programming for engineers in python

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 to Programming for engineers in python (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
 

More from James Wong

Multi threaded rtos
Multi threaded rtosMulti threaded rtos
Multi threaded rtosJames Wong
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningJames Wong
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryJames Wong
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningJames Wong
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksJames Wong
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsJames Wong
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceJames Wong
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesJames Wong
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileJames Wong
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheJames Wong
 
Abstract class
Abstract classAbstract class
Abstract classJames Wong
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisJames Wong
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaJames Wong
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJames Wong
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonJames Wong
 

More from James Wong (20)

Data race
Data raceData race
Data race
 
Multi threaded rtos
Multi threaded rtosMulti threaded rtos
Multi threaded rtos
 
Recursion
RecursionRecursion
Recursion
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Cache recap
Cache recapCache recap
Cache recap
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Object model
Object modelObject model
Object model
 
Abstract class
Abstract classAbstract class
Abstract class
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Inheritance
InheritanceInheritance
Inheritance
 

Recently uploaded

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Recently uploaded (20)

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

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