recitation 3 programming for engineers in python

Download Recitation 3 Programming for Engineers in Python

Post on 17-Dec-2015

213 views

Category:

Documents

0 download

Embed Size (px)

TRANSCRIPT

  • Slide 1
  • Recitation 3 Programming for Engineers in Python
  • Slide 2
  • Plan Modules / Packages Tuples Mutable / Imutable Dictionaries Functions: Scope Call by Ref / Call by Val Frequency Counter
  • Slide 3
  • Module Python Code Hierarchy Statement function Package
  • Slide 4
  • Modules All modules and their contents (functions, constants) can be found at http://docs.python.org/modindex.html >>> import math # mathematical functions >>> dir(math) ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] >>> math.pi # a constant 3.141592653589793 >>> math.sqrt(16) # a function 4.0 >>> math.log(8, 2) 3.0
  • Slide 5 >> os.times()[0] # user time 10.1244649">
  • Modules Cont. >>> import os #operating system interfaces >>> os.rename(my_file.txt, your_file.txt) >>> os.mkdir(new_dir) >>> for root, dirs, files in os.walk('lib/email'): print root, "consumes", print sum(getsize(join(root, name)) for name in files), print "bytes in", len(files), "non-directory files" >>> os.times()[0] # user time 10.1244649
  • Slide 6
  • Packages NumPy support for large, multi-dimensional arrays and matrices high-level mathematical functions SciPy Optimization linear algebra integration special functions signal and image processing And more
  • Slide 7
  • Installing Packages Download NumPy: http://sourceforge.net/projects/numpy/files/NumPy/ Choose Download numpy-1.6.1-win32-superpack- python2.7.exeDownload numpy-1.6.1-win32-superpack- python2.7.exe SciPy: http://sourceforge.net/projects/scipy/files/ Choose Download scipy-0.9.0-win32-superpack- python2.6.exeDownload scipy-0.9.0-win32-superpack- python2.6.exe
  • Slide 8
  • Mutable vs. Immutable Can we change lists? >>> a_list = [1,2,3] >>> a_list[2] 3 >>> a_list[2] = Inigo Montoya >>> a_list [1,2,Inigo Montoya] The assignment has mutated the list!
  • Slide 9
  • Mutable vs. Immutable What about strings? >>> name = Inigo Montoya >>> name[0] ' I' >>> name[5] ' >>> name[3] = t Traceback (most recent call last): File " ", line 1, in name[3] = 't' TypeError: 'str' object does not support item assignment Immutable!
  • Slide 10
  • Assignments to List Variables >>> orig_list = [1,2,3] >>> copy_list = orig_list >>> orig_list = [6,7,8,9] >>> copy_list [1,2,3] >>> orig_list [6,7,8,9] So far - no surprises
  • Slide 11
  • Assignments to List Variables >>> copy_list = orig_list >>> orig_list[0] = 1000 >>> orig_list [1000,7,8,9] >>> copy_list [1000,7,8,9] Surprise!
  • Slide 12
  • Assignments to List Variables List assignment orig_list = [6,7,8,9] creates: a list object, [6,7,8,9] a reference from the variable name, orig_list, to this object. [6,7,8,9] Memory orig_list
  • Slide 13
  • Assignments to List Variables The assignment copy_list = orig_list does not create a new object, just a new variable name, copy_list, which now refers to the same object. [6,7,8,9] Memory orig_list copy_list
  • Slide 14
  • Assignments to List Variables Mutating list elements, orig_list[0] = 1000, does not create a new object and does not change existing references. [1000,7,8,9] Memory orig_list copy_list
  • Slide 15
  • Tuples A tuple is just like a list, only it is immutable. Syntax: note the parentheses! >>> t = (dont,worry,be,happy) # definition >>> t (dont,worry,be,happy) >>> t[0] # indexing 'dont' >>> t[-1] # backwords indexing worry' >>> t[1:3] # slicing (worry,be)
  • Slide 16 >> t[0] = do# try to change Traceback (most recent call last): File " ", line 1, in t[0]=do typeerror: 'tuple' object does not support ite" title="Tuples >>> t[0] = do# try to change Traceback (most recent call last): File ">
  • Tuples >>> t[0] = do# try to change Traceback (most recent call last): File " ", line 1, in t[0]=do TypeError: 'tuple' object does not support item assignment No append / extend / remove in Tuples!
  • Slide 17
  • Tuples So what are tuples good for? Faster than lists Safe code When immutable types are required (coming next).
  • Slide 18
  • Dictionaries A dictionary is a set of key-value pairs. >>> dict_name = {key1:val1, key2:val2,} Keys are unique and immutable, values are not. Example: Map names to heights: >>> heights = {Alan Harper:1.76, John Smith:1.83, Walden Schmidt:1.90} >>> heights {'Walden Schmidt': 1.9, 'John Smith': 1.83, 'Alan Harper': 1.76} Note:The pairs order changed
  • Slide 19
  • Dictionaries Add a new person: >>> heights[Lyndsey Makelroy] = 1.70 >>> heights {'Lyndsey Makelroy': 1.7, 'Walden Schmidt': 1.9, John Smith': 1.83, 'Alan Harper': 1.76} What happens when the key already exists? >>> heights[John Smith] = 2.02 >>> heights {'Lyndsey Makelroy': 1.7, 'Walden Schmidt': 1.9, 'John Smith': 2.02, 'Alan Harper': 1.76} Solutions?
  • Slide 20
  • Dictionaries Idea: Add address to the key >>> heights = {[Alan Harper, Malibu]:1.76} Traceback (most recent call last): File " ", line 1, in heights = {['Alan Harper', 'Malibu']:1.76} TypeError: unhashable type: 'list Whats the problem? Fix: >>> heights = {(Alan Harper, Malibu):1.76} >>> heights {('Alan Harper', 'Malibu'): 1.76}
  • Slide 21
  • Dictionaries Useful methods: D.get(k[,d]) - D[k] if k in D, else d (default None). D.has_key(k) - True if D has a key k, else False D.items() - list of (key, value) pairs, as 2-tuples D.keys() - list of D's keys D.values() - list of D's values D.pop(k[,d]) - remove specified key and return the value. If key is not found, d is returned.
  • Slide 22
  • Functions Scope >>> a=3 >>> b=4 >>> linear combination(a,b) 11 # this is the correct value >>> a 3 >>> b 4 # b has NOT changed The change in y is local - inside the body of the function.
  • Slide 24
  • Functions Scope >>> x=3 >>> y=4 >>> linear_combination(x,y) 11 # this is the correct value >>> x 3 >>> y 4 The y in the calling environment and the y in the function are not the same variable!
  • Slide 25
  • Functions Call by Val / Call by Ref Functions have arguments that appear in their prototype: def linear_combination(x,y): When you call a function, you must assign values to the functions arguments: >>> linear_combination(3, 4) What happens when you pass variables? >>> linear_combination(a, b)
  • Slide 26
  • Functions Call by Val / Call by Ref What is the difference? Run ta3_switch.py to find out!
  • Slide 27
  • Functions Call by Val / Call by Ref What is the difference? Run ta3_add.py to find out!
  • Slide 28
  • b=[3, 4]a=[1,2] Functions Call by Val / Call by Ref There are two possibilities: Call by Value pass as value to x and bs value to y Call by Reference pass as address to x and bs address to y A_function x = 3 y = 4 a, b b=4a=3 a, b Another_function x y
  • Slide 29
  • Functions Call by Reference In Python Call by reference A function can mutate its parameters. When the address does not change, the mutations effect the original caller's environment. Remember: Assignment changes the address! That explains why y=2*y is not visible in the caller's environment.
  • Slide 30
  • Functions Call by Reference def increment(lst): for i in range(len(lst)): lst[i] = lst[i] +1 # no value returned Now let us execute it in the following manner >>> list1=[0,1,2,3] >>> increment(list1) >>> list1 [1, 2, 3, 4] # list1 has changed! lst was mutated inside the body of increment(lst). Such change occurs only for mutable objects.
  • Slide 31
  • Functions Call by Reference Consider the following function: def nullify(lst): lst=[ ] # no value returned Now let us execute it in the following manner >>> list1=[0,1,2,3] >>> nullify(list1) >>> list1 [0, 1, 2, 3] # list1 has NOT changed! Why?
  • Slide 32
  • Functions - Information Flow To conclude, we saw two ways of passing information from a function back to its caller: Using return value(s) Mutating a mutable parameter
  • Slide 33
  • Frequency Counter Assume you want to learn about the frequencies of English letters. You find a long and representative text and start counting. Which data structure will you use to keep your findings? s u p e r c a l i f r a g i l i s t i c e x p i a l i d o c i o u s
  • Slide 34
  • Frequency Counter str1 = 'supercalifragilisticexpialidocious # count letters charCount = {} for char in str1: charCount[char] = charCount.get(char, 0) + 1 # sort alphabetically sorted

Recommended

View more >