Download presentation
Presentation is loading. Please wait.
Published byRoland Harrington Modified over 8 years ago
1
Computation for Physics 計算物理概論 Python Programming for Physicists
2
What is Python?
3
Python Programming Language Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming styles. Python features a fully dynamic type system and automatic memory management,
4
PEP 20 “The Zen of Python” PEP=Python Enhancement Proposal Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Readability counts. Guido van Rossum Creator of python Benevolent Dictator for Life
5
Programming Language High-level language Low-level language
6
Compilation v.s. Interpretation SOURCE CODE SOURCE CODE INTERPRETER OUTPUT SOURCE CODE SOURCE CODE OUTPUT COMPILER OBJECT CODE OBJECT CODE EXECUTOR
7
Python: Interpreted Language Interactive mode – You type Python programs and the interpreter displays the result. Script mode – You store code in a file and use the interpreter to execute the contents of the file.
8
PYTHON DEVELOPMENT ENVIRONMENT
9
Python(x,y) Scientific-oriented Python Distribution based on Qt and Spyder Python(x,y) is a free scientific and engineering development software for numerical computations, data analysis and data visualization based on Python programming language, Qt graphical user interfaces and Spyder interactive scientific development environment. https://code.google.com/p/pythonxy/
10
Download Python(x,y) Download from one of the mirrors
11
Python(x,y) Plugins=Python Packages IDLE, IPython – Development environment NumPy – Multidimensional arrays support and basic operations SciPy – Advanced math, signal processing, optimization, statistics Matplotlib – 2D plotting library VPython – Creation of 3D interactive models of physical systems SymPy – Symbolic Mathematics Library
12
IDLE Integrated DeveLopment Environment IDLE is the Python IDE built with the Tkinter GUI toolkit. IDLE has the following features: – coded in 100% pure Python, using the Tkinter GUI toolkit – cross-platform: works on Windows and Unix – multi-window text editor with multiple undo, Python colorizing and many other features, e.g. smart indent and call tips – Python shell window (a.k.a. interactive interpreter) – debugger (not complete, but you can set breakpoints, view and step) It is a part of the standard library and is described in the reference manual: http://www.python.org/doc/current/lib/idle.html The source code for IDLE is included in the standard library. More information on developing IDLE can be found at http://docs.python.org/devguide/
13
IDLE Integrated development environment Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>>
14
Start IDLE 開始 所有程式 python(x,y) IDLE
15
File New Window
16
File Save As
17
Run Run Module
18
Python Shell
19
PYTHON PROGRAMMING LANGUAGE
20
What is a Program? A sequence of instructions that specifies how to perform a computation Basic instructions – Input – Output – Math – Conditional execution – Repetition
21
What is Debugging Programming is error-prone Programming errors=bugs The process of tracking bugs down=debugging Three kinds of errors Syntax errors Runtime errors Semantic errors
22
First Program=“Hello, World!” Traditionally, the first program you write in a new language is to display the words – “Hello, World” print(‘Hello, World!’) Case-sensitive
23
Variables, Expressions, Statements
24
Variables, Values, Stage Diagram State diagram – variables value message ’And now for something’ n 17 pi 3.1415926535 z 1+3i
25
Assignment Statement “=“ is an “assignment” message = ’And now for something’ n = 17 pi = 3.1415926535 z = 1+3j 2*x=y – Syntax Error
26
data types integer=integer number float=floating point number complex=complex floating point number str=string >>> type(17) >>> type(3.2) >>> type(1+3j) >>> type(‘Hello, World!’)
27
data types integer=integer number float=floating point number complex=complex floating point number str=string >>> type(n) >>> type(pi) >>> type(z) >>> type(message)
28
Dynamically Typed >>> x=3 # x is of integer type >>> x=3.0 # x is of float type >>> x=‘blah’ # x is of string type >>> x=[3,3.0,’blah’] # x is of list type
29
Variable Names & Keywords Keywords – The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names – and – if – else – while – …etc
30
Operators & Operand + – addition: x+y - – subtraction: x-y * – multiplication: x*y / – division: x/y ** – exponentizaton x**y // – the integer part of x/y: 14.5//3.6 4.0, 14.5//3.7 3.0 % – module=remainder after x/y: 1.5%0.4 0.3
31
Expression & Statement An expression is a combination of values, variables, and operators. – x – x+17 A statement is a unit of code that the Python interpreter can execute. – x=3 – print(‘Hello’)
32
Interactive & Script Mode Interactive mode Script mode Major difference – Python actually evaluates the expression, but it doesn’t display the value unless you tell it to
33
Order of Operations Rue of precedence Parentheses Exponentiation Multiplication and Division Left to right for operators with the same precedence
34
Comments It is a good idea to add notes to your programs to explain in natural language what the program is doing. Comments start with the # symbol # compute the velocity v=dx / dt v=dx / dt # compute the velocity
35
x=1 print(x) variable assignment statement
36
Variables Types Integer – x=1 Float – x=1.5 – x=1.0 – x=float(1) Complex – x=1.5+2.0j – x=1.5+0j – x=complex(1.5)
37
string String literals can be written enclosed in either two single or two double quotes x='This is a string' x="This is a string" y='1.234' # create a string with value ‘1.234’ y=1.234 # create a real number with value 1.234 z='x=1' # create a string with value ‘x=1’
38
type conversion functions string to integer >>> int(‘32’) 32 >>> int(3.999) 3 >>> int(-2.3) -2 >>> int('Hello') ValueError: invalid literal for int() with base 10: 'hello' >>> int('3.999') ValueError: invalid literal for int() with base 10: '3.999'
39
Help(int) >>>help(int) Help on class int in module __builtin__: class int(object) | int(x[, base]) -> integer | | Convert a string or number to an integer, if possible. A floating point | argument will be truncated towards zero (this does not include a string | representation of a floating point number!) When converting a string, use | the optional base. It is an error to supply a base when converting a | non-string. If base is zero, the proper base is guessed based on the | string content. If the argument is outside the integer range a | long object will be returned instead.
40
Type conversion functions string to float >>> float(‘32’) 32.0 >>> (‘3.14159’) 3.14159 >>> int(float(‘3.999’)) 3 class float(object) | float(x) -> floating point number | | Convert a string or number to a floating point number, if possible.
41
type conversion functions ‘blah’ to complex >>> complex(32) (32+0j) >>> complex(‘3.2’) (3.2+0j) >>> complex(3+j) NameError: name 'j' is not defined >>> complex(3+0j) (3+0j) >>> complex(3+1j) (3+1j) >>> complex(‘3+j’) (3+1j) >>> complex(‘3+0j’) (3+0j) >>> complex(‘3+1j’) (3+1j)
42
Output Statements >>> x = 1 >>> print(x) 1 >>> x=1 >>> y=2 >>> print(x,y) 1 2 >>> print("The value of x is", x, "and y=",y) The value of x is 1 and y=2
43
Input Statement >>> x = input("Enter the value of x:”) (The computer will stop and wait) >>> print("The value of x is ",x) >>> x = input("Enter the value of x:") (You enter "Hello") >>> print("The value of x is ",x) The value of x is Hello
44
Input Statement Convert input string to float temp = input("Enter the value of x: ") x=float(temp) print("The value of x is ",x) x = float(input("Enter the value of x: ")) print("The value of x is ",x)
45
Python 3 v.s. Python 2 Include following statement in your code from __future__ import division, print_function Division return a floating value – 3/2 1 # python 2 – 3/2 1.5 # python 3 – 4/2 2 # python 2 – 4/2 2.0 #python 3 Print is a statement – print "The energy is ", E # python 2 – print("The energy is ",E) # python 3
46
Python 3 v.s. Python 2 Input returns a string – In Python 3 the input function always returns a string – x=input() – you enter ‘2.5’ – type(x) # python 2 – type(x) # python 3 – x=raw_input() – type(x) # python 2
47
Python 3 v.s. Python 2 Iterators v.s. List – range(10) [0,1,2,3,4,5,6,7,8,9] # python 2 – range(10) range(0,10) # python 3 – list(range(10)) [0,1,2,3,4,5,6,7,8,9] # python 3 – x = [1,2,3] – map(log,x) [0.0, 0.69…, 1.09…] # python 2 – map(log,x) # python 3 – list(map(log,x)) [0.0, 0.69…, 1.09…] # python 3
48
“x=a+b” is an assignment statement! x = 1 – x 1 x = x+1 – x x+1 – temp = x+1 – x=temp x = x**2 – 2 – x x**2 - 2
49
Python Modifiers x += 1 – x = x + 1 x -= 4 – x = x - 4 x *= -2.6 – x = x*(-2.6) x /= 5*y – x = x / (5*y) x //= 3.4 – x = x // 3.4
50
Assignment of Multiple Variables x, y = 1, 2.5 – x = 1 – y = 2.5 x, y = 2*z+1, (x+y)/3 – temp1 = 2*z+1 – temp2 = (x+y)/3 – x = temp1 – y = temp2
51
Assignment of Multiple Variables You can interchange of values of two variables x, y = y, x – temp = y – y = x – x = temp
52
Try: A ball dropped from a tower Write a program to ask the user to enter h the height of the tower and a time interval t, then prints the height of the ball above the ground at time t after it is dropped.
53
A ball dropped from a tower Simple version h = float(input(“Enter the height of the tower: ")) t = float(input("Enter the time interval: ")) s = 9.81*t**2/2 print("The height of the ball is", h-s, "meters") To make it more readable g = 9.81 s = g*t**2/2
54
Another ball dropped from a tower A ball is dropped from a tower of height h with initial velocity zero. Write a program that asks the user to enter the height in meters and the calculates and prints the time the ball takes until it hits the ground.
55
Functions, Packages, & Modules >>> from math import log >>> x = log(2.5) log(...) log(x[, base]) Return the logarithm of x to the given base. If the base not specified, returns the natural logarithm (base e) of x.
56
math—Mathematical Functions from math import * Functions: log log10 exp sin, cos, tan asin, acos, atan sinh, cosh, tanh sqrt Constants: pi e
57
Try: Converting polar coordinates Get the user to enter the value of r and θ Convert those values to Cartesian coordinates Print out the results
58
Converting polar coordinates from math import sin, cos, pi r = float(raw_input("Enter r: ")) d = float(raw_input("Enter theta in degrees: ")) theta = d*pi/180 x = r*cos(theta) y = r*sin(theta) print("x= ",x, "y= ",y)
59
Comment Statements from math import sin, cos, pi # Ask the user for the values of the radius and angle r = float(input(“Enter r: “)) d = float(input(“Enter theta in degrees: “)) # Convert the angle to radians theta = d*pi/180 # Calculate the equivalent Cartesian coordinates x = r*cos(theta) y = r*sin(theta) print(“x= “,x,”y= “,y) # Print out the results
60
Multiline \ 1+2\ 3
61
help >>> help(sum) Help on built-in function sum in module __builtin__: sum(...) sum(sequence[, start]) -> value Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the sequence is empty, returns start.
62
Branching
63
Boolean expressions >>>5 == 5 True >>>5 == 6 False >>>type(True) >>>type(False)
64
Relational Operators x == y# x is equal to y x != y# x is not equal to y x > y# x is greater than y x < y# x is less than y x >= y# x is greater than or equal to y x <= y# x is less than or equal to y
65
Logical Operators and or not >>> 3>1 and 3>2 True >>> 3>1 or 3<2 Ture >> not (3>1) False
66
Numerical Values of True & False >>>int(True) 1 >>>int(False) 0 >>>0==False True >>>1==True True >>>2==True False
67
Conditional Execution if x > 0: print(‘x is positive’) print(‘Hello, World!’) Condition Compound statements
68
Alternative Execution if x % 2 ==0: print(‘x is even’) else: print(‘x is odd’)
69
Chained Conditionals if x < y: print(‘x is less than y’) elif x > y: print(‘x is greater than y’) else: print(‘x and y are equal’) elif=“else if”
70
Chained Conditionals if choice == ‘a’ draw_a() elif choice == ‘b’ draw_b() elif choice == ‘c’ draw_c() function call
71
Nested Conditionals if x == y: print(‘x and y are equal’) else: if x < y: print(‘x is less than y’) else: print(‘x is greater than y’)
72
Use Logic Operators to Simplify if 0 < x: if x < 10: print(‘x is ……’) if 0 < x and x < 10: print(‘x is ……’)
73
If (anything): 0 is interpreted as False Any other number is interpreted as True Empty lists and objects return False Non-empty lists and objects return True
74
if (anything): >>>if 0:... print(‘x’) >>>if 1:... print(‘x’) x >>>if 1.1:... print(‘x’) x >>>d=[] >>>if d:... print(‘x’) >>>d=[1,2] >>>if 1.1:... print(‘x’) x
75
Iteration
76
The ‘While’ Statement n=10 while n > 0: print(n) n = n-1 Loop You should change the value of one or more variables, otherwise it will become an infinite loop
77
Will the Loop Terminates for all n? n = 3 while n != 1: print(n) if n%2 == 0:# n is even n = n//2 else:# n is odd n = n*3+1 3,10,5,16,8,4,2,1
78
Break while True: line = raw_input(‘> ‘) if line == ‘done’: break print(line) print(‘finished’)
79
Try: Fibonacci Sequence Sequence of integers in which each is the sum of previous two, starting with 1,1 1, 1, 2, 3, 5, 8, 13, 21 f1 = 1 f2 = 1 next = f1 + f2 while f1 <= 1000: print(f1) f1 = f2 f2 = next next = f1 + f2
80
Fibonacci Sequence, Simplified f1, f2 = 1, 1 while f1 < 1000: print(f1) f1, f2 = f2, f1+f2
81
Try: Catalan Numbers
82
Try: Square Roots
83
Newton’s Method, Interactively >>>a=4.0 >>>x=3.0 >>>y=(x+a/x)/2 >>>print(y) 2.16666666667 >>>x=y >>>y=(x+a/x)/2 >>>print(y) 2.00641025641
84
Square Roots while True: print(x) y = (x + a/x ) / 2 if y == x: break x = y
85
Square Roots (Safer Check) epsilon = 0.0000001 while True: print(x) y = (x + a/x ) / 2 if abs(y-x) < epsilon: break x = y
86
User-Defined Functions
87
Factorial Function def factorial(n): f = 1.0 for k in range(1,n+1) f *= k return f a = factorial(10) b = factorial(r+2*s) Local variables Argument
88
Distance Function def distance(r, theta, z): x = r*cos(theta) y = r*sin(theta) d = sqrt(x**2+y**2+z**2) return d D = distance(2.0,0.1,-1.5) Multiple arguments
89
Use “def” Statement to Define a Function def add(arg1, arg2) x=arg1+arg2 return x def power(x,y) if x <=0: return 0 else return x**y
90
Return Arbitrary Type def cartesian(r,theta): x = r*cos(theta) y = r*sin(theta) position = [x,y] return position def f(z): # Some calculations here... return a,b x,y = f(1)
91
Return No Value def print_vector(r): print("(",r[0],r[1],r[2],")")
92
Map User-defined Function to a List def f(x): return 2*x-1 newlist = list(map(f,oldlist))
93
Try: Square Root Function Write your own square root function Input a and epsilon Output square root of a Compare the result with built-in function sqrt()
94
Lists
95
Build-in Type: List List=[element1, elemen2, element3,…] r = [ 1, 1, 2, 3, 5, 8, 13, 21] print(r) [ 1, 1, 2, 3, 5, 8, 13, 21] x = 1.0 y = 1.5 z = -2.2 r = [x,y,z] r = [ 2*x, x+y, z/sqrt(x**2+y**2) ]
96
Access List Elements >>> r = [ 1.0, 1.5, -2.2] >>> r[0] 1.0 >>> r[4] Traceback (most recent call last): File " ", line 1, in IndexError: list index out of range >>> r[-1] -2.2 The index number starts at zero
97
Modify List Elements >>>r = [ 1.0, 1.5, -2.2] >>>r[0] = 3.5 1.0 >>>r [3.5, 1.5, -2.2]
98
List Operations >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> print(c) [1, 2, 3, 4, 5, 6] >>> [0] * 4 [0, 0, 0, 0] >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
99
List Functions Functions that take ‘list’ as an argument >>> r = [ 1.0, 1.5, -2.2] >>> sum(r) 0.3 >>> sum(r)/len(r) 0.1
100
Meta-Function: map Apply functions to all elements of a list map(log, r) take the natural logarithm of each element of a list r from math import log r = [ 1.0, 1.5, 2.2 ] logr = list(map(log,r)) print(logr) [0.0, 0.4054651081, 0.7884573603]|
101
List Methods: Add an Element >>>r = [ 1.0, 1.5, -2.2 ] >>>x = 0.8 >>>r.append(2*x+1) >>>print(r) [1.0, 1.5, -2.2, 2.6] >>>t1 = [‘a’, ‘b’, ‘c’] >>>t2 = [‘d’, ‘e’] >>>t1.extend(t2) >>>print(t1) [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
102
Starts from an Empty List >>>r=[] >>>r.append(1.0) >>>r.append(1.5) >>>r.append(-2.2) >>>print(r) [1.0, 1.5, -2.2]
103
List Methods: Remove am Element >>>r = [ 1.0, 1.5, -2.2, 2.6 ] >>>r.pop() >>>print(r) [1.0, 1.5, -2.2] >>>t =[‘a’, ‘b’, ‘c’] >>>x = t.pop(1) >>>print(t) >>>print(x)
104
Remove a known Element >>>t = [‘a’, ‘b’, ‘c’] >>>t.remove(‘b’) >>>print(t) [‘a’, ‘c’]
105
Traveling a List: For Loop r = [ 1, 3, 5 ] for n in r: print(n) print(2*n) print("Finished") 1 2 3 6 5 10 Finished
106
Traveling a List: For Loop for i in [3, ‘Hello’, 9.5]: print i 3 Hello 9.5 for x in []: print(‘This never happens’)
107
Run Some Code a Number of Times r = [0, 1, 2, 3, 4 ] for i in r: blah print(‘Finished’) If we want to loop 10000000 times?
108
Built-in Function: range() range(5) gives [0, 1, 2, 3, 4] range(2,8) gives [2, 3, 4, 5, 6, 7] range(2,20,3) gives [2, 5, 8, 11, 14, 17] range(20,2,-3) gives [20, 17, 14, 11, 8, 5]
109
range(integer) p = 10 q = 2 range(p/q) (error!) range(p//q) (ok!)
110
Performing a Sum
111
List Slices: list[lower:upper:step] Inclusive lower element index (default=0) Exclusive upper element index (default=Length) >>>l=[1,2,3,4,5] >>>l[0:4] [1,2,3,4] >>>l[0:4:2] [1,3] >>>l[:4] [1,2,3,4] >>>l[2:] [3,4,5] >>>l[::2] [1,3,5]
112
List Comprehensions >>>[i*i for i in range(5)] [0, 1, 4, 9, 16] >>>[k*5 for k in [4,8,9]] [20, 40, 45] >>>[q**(0.5) for q in [4,6,9]] [2.0, 3.0, 4.0] >>>[ k%2 == 0 for k in range(5)] [True, False, True, False, True]
113
Examples
114
Try: Emission Line of Hydrogen R = 1.097e-2 for m in [1,2,3]: print("Series for m =", m) for k in [1,2,3,4,5]: n=m+k invlambda = R*(1/m**2-1/n**2) print(" ",1/invlambda," nm")
115
Use range() Function to Simplify R = 1.097e-2 for m in range(1,4): print("Series for m =",m) for n in range(m+1,m+6): invlambda = R*(1/m**2-1/n**2) print(" ",1/invlambda," nm")
116
Try: The Madelung Constant In condensed matter physics the Madelung constant gives the total electric potential felt by an atom in a solid. It depends on the charges on the other atoms nearby and their locations. Consider for instance solid sodium chloride—table salt. The sodium chloride crystal has atoms arranged on a cubic lattice, but with alternating sodium and chlorine atoms, the sodium ones having a single positive charge +e and the chlorine ones a single negative charge −e, where e is the charge on the electron. If we label each position on the lattice by three integer coordinates (i, j, k), then the sodium atoms fall at positions where i + j + k is even, and the chlorine atoms at positions where i + j + k is odd.
117
Try: The Madelung Constant Consider a sodium atom at the origin, i = j = k = 0, the spacing of atoms on the lattice is a. The distance from the origin to the atom at position (i, j, k) is The potential at the origin created by such an atom is The sign of the expression depending on whether i + j + k is even or odd. The total potential felt by the sodium atom is the sum of this quantity over all other atoms. Assume a cubic box around the sodium at the origin, with L atoms in all directions. M=Madelung constant is the value of M when L → ∞, but one can get a good approximation just by using a large value of L.
118
Try: The Madelung Constant Write a program to calculate and print the Madelung constant for sodium chloride. Use as large a value of L as you can, while still having your program run in reasonable time— say in a minute or less.
119
The Semi-Empirical Mass Formula
120
Try: Prime Factors and Prime Numbers Suppose we have an integer n and we want to know its prime factors. The prime factors can be calculated relatively easily by dividing repeatedly by all integers from 2 up to n and checking to see if the remainder is zero.
121
Try: Factor List Input an integer n Output the factor list Input=28 Output=[2,2,7]
122
Try: Factorlist def factor(n): factorlist = [] k = 2 while k <= n: while n%k == 0: factorlist.append(k) n //= k #n=n//k k += 1 return factorlist
123
Try: Optimization: Find All the Primes Finds all the primes up to n. Create a list to store the primes, which starts out with just the one prime number 2 in it. Look over n=2 to 10000 Call factor(n) If the factorlist contains only one element, the n is a prime. Add n to the prime list. Slow and stupid, any better way?
124
Try: Optimization: Find All the Primes Finds all the primes up to n. Create a list to store the primes, which starts out with just the one prime number 2 in it. For each number n from 3 to 10000 check whether the number is divisible by any of the primes in the list up to and including. As soon as you find a single prime factor you can stop checking the rest of them—you know n is not a prime. If you find no prime factors or less then n is prime and you should add it to the list. You can print out the list all in one go at the end of the program, or you can print out the individual numbers as you find them.
125
Time your code! from time import * start_time=time() blah end_time=time() used_time=end_time-start_time
126
Good Programming Style
127
Include comments in your programs. Use meaningful variable names. Use the right types of variables. Import functions first. Give your constants names. Employ user-defined functions, where appropriate. Print out partial results and updates throughout your program. Lay out your programs clearly. Don’t make your programs unnecessarily complicated.
128
Dictionary
129
Dictionary {Key:Value} >>>eng2sp = dict() >>>print(eng2sp) {} >>>eng2sp[‘one’]='uno' >>>print(eng2sp) {'one':'uno'} >>>eng2sp={'one':'uno','two':'dos','three':'tres'} >>>print(eng2sp} {'one':'uno','three':'tres','two':'dos'} >>>print(eng2sp['two']) dos >>>print(eng2sp['four']) KeyError: 'four' >>>len(eng2sp) 3
130
Something as a Key or a Value? >>>'one' in eng2sp True >>>'uno' in eng2sp False >>>vals = eng2sp.values() >>>'uno' in vals True Python2's "has_key()" is moved in Python3
131
Dictionary as a Set of Counters Want to count how many times each letter appears in a given string. Create 26 variables, one for each letter of the alphabet. Create a list with 26 elements. Convert each character to a number which is used as an index. Create a a dictionary with characters as key and counter as values.
132
Dictionary as a Set of Counters def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d >>>h = histogram('brontosaurus') >>>print(h) {'a':1, 'b':1, 'o':2, 'n':1, 's':2, 'r':2, 'u':2, 't':1 }
133
Dictionaries and Lists def invert_dict(d): inverse = dict() for key in d: val = d[key] if val not in inverse: inverse[val] = [key] else: inverse[val].append(key) return inverse >>> hist = histogram('parrot') >>> print hist {'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1} >>> inverse = invert_dict(hist) >>> print inverse {1: ['a', 'p', 't', 'o'], 2: ['r']}
134
Fibonacci Function fibonacci(0)=0 fibonacci(1)=1 fibonacci(n)=ibonacci(n-1)+ibonacci(n-2) def fibonacci (n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2)
135
Keep Tracks of the Values known = {0:0, 1:1} def fibonacci(n): if n in known: return known[n] res = fibonacci(n-1) + fibonacci(n-2) known[n] = res return res
136
Tuples
137
Tuples are Immutable A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.
138
tuple=a comma-separated list of values >>>t = 'a', 'b', 'c', 'd', 'e' >>>t = ('a', 'b', 'c', 'd', 'e') >>>t1 = 'a', >>>type(t1) >>>t2 = ('a') >>>type(t2)
139
Built-in Function: tuple >>>t = tuple() >>>print(t) () >>>t = tuple('lupins') >>>print(t) ('l', 'u', 'p', 'i', 'n', 's') >>>t = tuple(['l','u','p','i','n',s']) >>>print(t) ('l', 'u', 'p', 'i', 'n', 's')
140
Most List Operators also Work on Tuples >>> t = ('a', 'b', 'c', 'd', 'e') >>> print t[0] 'a' >>> print t[1:3] ('b', 'c') >>> t[0] = 'A' TypeError: object doesn't support item assignment >>> t = ('A',) + t[1:] >>> print t ('A', 'b', 'c', 'd', 'e')
141
Tuple Assignment >>>a, b = b, a >>>a, b = 1, 2, 3 ValueError: too many values to unpack >>>addr = 'monty@python.org' >>>uname,domain = addr.split('@') >>>print(uname) monty >>>print(domain) python.org
142
Tuples ad Return Values >>>t = divmod(7,3) >>>print(t) (2, 1) >>>quot, rem = divmod(7,3) >>>print(quot) 2 >>>print(rem) 1 def min_max(t): return min(t), max(t)
143
Variable-length argument tuples Functions can take a variable number of arguments A parameter name that begins with * gathers arguments into a tuple def printall(*agr): print args >>>printall(1, 2.0, '3') (1, 2.0, '3')
144
Scatter divmod takes exactly two arguments; it doesn't work with a tuple But you can scatter the tuple >>>t = (7,3) >>>divmod(t) TypeError: divmod expected 2 arguments, got 1 >>>divmod(*t) (2, 1)
145
Lists and Tuples zip is a built-in function that takes two or more sequences and "zip" them into a list/iterator of tuples where each tuple contains one element from each sequence. >>>s = 'abc' >>>t = [0,1,2] >>>zip(s, t) [('a',0),('b',1),('c',2)] >>>zip('Anne', 'Elk') [('A','E'),('n','l'),('n','k')]
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.