Download Python

Document related concepts
no text concepts found
Transcript
Python "Nästan som MATLAB… fast bä@re" Lund University / Lunarc / Python Lecture 1 Python •  Skapades i början av 1990-­‐talet –  Guido van Rossum –  Få@ si@ namn från Monty Python •  Stöd för flera programmeringsparadigmer –  FunkPonell programmering –  Objektorienterad programmering •  Ren programkod –  Inga radavslut med semikolon –  Indrag bestämmer kodblock Lund University / Lunarc / Python Lecture 1 Python •  Skriptspråk –  Översä@s rad för rad –  Ingen kompilering och länkning Pll maskinkod •  Dynamisk typning –  Variabler kan byta datatyp under exekvering a = ”hejsan!” a = 256 a = True Lund University / Lunarc / Python Lecture 1 Python •  Skräpsamling (garbage collecPon) –  Variabler som inte används längre rensas automaPskt for i in range(10): b = i + 2 print b # b automatiskt rensad Lund University / Lunarc / Python Lecture 1 Python •  InterakPvt Lund University / Lunarc / Python Lecture 1 Tal >>> 2+2 4 >>> # This is a comment ... 2+2 4 >>> 2+2 # and a comment on the same line as code 4 >>> (50-­‐5*6)/4 5 >>> # Integer division returns the floor: ... 7/3 2 >>> 7/-­‐3 -­‐3 Lund University / Lunarc / Python Lecture 1 Variabler >>> width = 20 >>> height = 5*9 >>> width * height 900 >>> x = y = z = 0 # Zero x, y and z >>> x 0 >>> y 0 >>> z 0 Lund University / Lunarc / Python Lecture 1 Fly@al >>> 3 * 3.75 / 1.5 7.5 >>> 7.0 / 2 3.5 Lund University / Lunarc / Python Lecture 1 Teckensträngar >>> 'spam eggs' 'spam eggs' >>> 'doesn\'t' "doesn't" >>> "doesn't" "doesn't" >>> '"Yes," he said.' '"Yes," he said.' >>> "\"Yes,\" he said." '"Yes," he said.' >>> '"Isn\'t," she said.' '"Isn\'t," she said.' Lund University / Lunarc / Python Lecture 1 Teckensträngar hello = "This is a rather long string containing\n\ several lines of text just as you would do in C.\n\ Note that whitespace at the beginning of the line is\ significant." print hello This is a rather long string containing several lines of text just as you would do in C. Note that whitespace at the beginning of the line is significant. Lund University / Lunarc / Python Lecture 1 Teckensträngar hello = r"This is a rather long string containing\n\ several lines of text much as you would do in C." print hello This is a rather long string containing\n\
several lines of text much as you would do in C.
Lund University / Lunarc / Python Lecture 1 Teckensträngar print """ Usage: thingy [OPTIONS] -­‐h Display this usage message -­‐H hostname Hostname to connect to """ Usage: thingy [OPTIONS] -­‐h Display this usage message -­‐H hostname Hostname to connect to Lund University / Lunarc / Python Lecture 1 Teckensträngar >>> word = 'Help' + 'A' >>> word 'HelpA' >>> '<' + word*5 + '>' '<HelpAHelpAHelpAHelpAHelpA>' >>> word[4] 'A' >>> word[0:2] 'He' >>> word[2:4] 'lp' Lund University / Lunarc / Python Lecture 1 Teckensträngar >>> word[:2] # The first two characters 'He' >>> word[2:] # All but the first two characters 'lpA' Lund University / Lunarc / Python Lecture 1 Teckensträngar Teckensträngar kan inte ändras
>>> word[0] = 'x' Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object doesn't support item assignment >>> word[:1] = 'Splat' Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object doesn't support slice assignment Lund University / Lunarc / Python Lecture 1 Teckensträngar >>> word[-­‐1] # The last character 'A' >>> word[-­‐2] # The last-­‐but-­‐one character 'p' >>> word[-­‐2:] # The last two characters 'pA' >>> word[:-­‐2] # All but the last two characters 'Hel' >>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34 Lund University / Lunarc / Python Lecture 1 Lista • 
• 
• 
• 
• 
Sammansa@ datatyp Används för a@ gruppera ihop värden Olika datatyper i samma lista Börjar med index 0 Individuella värden kan ändras Lund University / Lunarc / Python Lecture 1 Lista >>> a = ['spam', 'eggs', 100, 1234] >>> a ['spam', 'eggs', 100, 1234] >>> a[0] 'spam' >>> a[3] 1234 >>> a[-­‐2] 100 >>> a[1:-­‐1] ['eggs', 100] >>> a[:2] + ['bacon', 2*2] ['spam', 'eggs', 'bacon', 4] >>> 3*a[:3] + ['Boe!'] ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!'] Lund University / Lunarc / Python Lecture 1 Lista >>> # Replace some items: >>> a ... a[0:2] = [1, 12] ['spam', 'eggs', 100, 1234] >>> a >>> a[2] = a[2] + 23 [1, 12, 123, 1234] >>> a >>> # Remove some: ['spam', 'eggs', 123, 1234] ... a[0:2] = [] >>> a [123, 1234] >>> # Insert some: ... a[1:1] = ['bletch', 'xyzzy'] >>> a [123, 'bletch', 'xyzzy', 1234] >>> a[:0] = a # Insert (a copy of) itself at the beginning >>> a [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] Lund University / Lunarc / Python Lecture 1 Lista >>> len(a) 8 Lund University / Lunarc / Python Lecture 1 >>> q = [2, 3] >>> p = [1, q, 4] >>> len(p) 3 >>> p[1] [2, 3] >>> p[1][0] 2 >>> p[1].append('xtra') >>> p [1, [2, 3, 'xtra'], 4] >>> q [2, 3, 'xtra'] Programmering >>> # Fibonacci series: ... # the sum of two elements defines the next ... a, b = 0, 1 >>> while b < 10: Kodblock som exekveras ... print b I while-­‐satsen ... a, b = b, a+b Indrag ... 1 1 2 3 5 8 Lund University / Lunarc / Python Lecture 1 Programmering utskriY >>> i = 256*256 >>> print 'The value of i is', i The value of i is 65536 >>> a, b = 0, 1 >>> while b < 1000: ... print b, ... a, b = b, a+b ... 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 Lund University / Lunarc / Python Lecture 1 Flödeskontroll Lund University / Lunarc / Python Lecture 1 if-­‐satser >>> x = int(raw_input("Please enter an integer: ")) >>> if x < 0: ... x = 0 ... print 'Negative changed to zero' ... elif x == 0: ... print 'Zero' ... elif x == 1: ... print 'Single' ... else: ... print 'More' ... Lund University / Lunarc / Python Lecture 1 for-­‐loopar >>> # Measure some strings: ... a = ['cat', 'window', 'defenestrate'] >>> for x in a: ... print x, len(x) ... cat 3 window 6 defenestrate 12 Lund University / Lunarc / Python Lecture 1 range() funkPonen >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(-­‐10, -­‐100, -­‐30) [-­‐10, -­‐40, -­‐70] Obs endast heltal! Lund University / Lunarc / Python Lecture 1 range() funkPonen >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print i, a[i] ... 0 Mary 1 had 2 a 3 little 4 lamb Lund University / Lunarc / Python Lecture 1 break, conPnue och else i loopar •  break –  avbryter en loop •  conPnue –  fortsä@er Pll nästa iteraPon •  else –  anropas när loopen är slut, men inte om break använts Lund University / Lunarc / Python Lecture 1 break, conPnue och else i loopar >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print n, 'equals', x, '*', n/x ... break ... else: ... # loop fell through without finding a factor ... print n, 'is a prime number' ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 Lund University / Lunarc / Python Lecture 1 pass-­‐satser >>> while True: ... pass # Busy-­‐wait for keyboard interrupt ... Lund University / Lunarc / Python Lecture 1 FunkPoner >>> def fib(n): # write Fibonacci series up to n ... """Print a Fibonacci series up to n.""" Kodblock som 8llhör ... a, b = 0, 1 ... while b < n: funk8onen ... print b, ... a, b = b, a+b ... >>> # Now call the function we just defined: ... fib(2000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 Lund University / Lunarc / Python Lecture 1 FunkPoner -­‐ returvärde >>> def fib2(n): # return Fibonacci series up to n ... result = [] ... a, b = 0, 1 ... while b < n: ... result.append(b) # see below ... a, b = b, a+b ... return result ... >>> f100 = fib2(100) # call it >>> f100 # write the result [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] Lund University / Lunarc / Python Lecture 1 Standard argument ”Redan ifyllda parametrar” def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return 1 if ok in ('n', 'no', 'nop', 'nope'): return 0 retries = retries -­‐ 1 if retries < 0: raise IOError, 'refusenik user' print complaint ask_ok('Do you really want to quit?') ask_ok('OK to overwrite the file?', 2) Lund University / Lunarc / Python Lecture 1 Nyckeordsargument def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print "-­‐-­‐ This parrot wouldn't", action, print "if you put", voltage, "Volts through it." print "-­‐-­‐ Lovely plumage, the", type print "-­‐-­‐ It's", state, "!" parrot(1000) parrot(action = 'VOOOOOM', voltage = 1000000) parrot('a thousand', state = 'pushing up the daisies') parrot('a million', 'bereft of life', 'jump') parrot() # required argument missing parrot(voltage=5.0, 'dead') # non-­‐keyword argument following keyword parrot(110, voltage=220) # duplicate value for argument parrot(actor='John Cleese') # unknown keyword Lund University / Lunarc / Python Lecture 1 Datastrukturer Lund University / Lunarc / Python Lecture 1 Mer om listor •  append(x) -­‐ Lägger Pll x i slutet av listan •  extend(L) -­‐ Lägg Pll alla element i listan L sist •  remove(x) -­‐ Tar bort först förekomsten av x i listan •  pop([i]) -­‐ Returnerar och tar bort sista elementet i listan •  index(x) -­‐ Returnerar x index i lista •  count(x) -­‐ Returnerar antalet förekomster av x i listan •  sort() -­‐ sorterar listan •  reverse() -­‐ motsatsen Lund University / Lunarc / Python Lecture 1 Mer om listor >>> a = [66.6, 333, 333, 1, 1234.5] >>> print a.count(333), a.count(66.6), a.count('x') 2 1 0 >>> a.insert(2, -­‐1) >>> a.append(333) >>> a [66.6, 333, -­‐1, 333, 1, 1234.5, 333] >>> a.index(333) 1 >>> a.remove(333) >>> a [66.6, -­‐1, 333, 1, 1234.5, 333] >>> a.reverse() >>> a [333, 1234.5, 1, 333, -­‐1, 66.6] >>> a.sort() >>> a [-­‐1, 1, 66.6, 333, 333, 1234.5] Lund University / Lunarc / Python Lecture 1 del funkPonen >>> a = [-­‐1, 1, 66.6, 333, 333, 1234.5] >>> del a[0] >>> a [1, 66.6, 333, 333, 1234.5] >>> del a[2:4] >>> a [1, 66.6, 1234.5] >>> del a Lund University / Lunarc / Python Lecture 1 Index eller “dicPonaries” •  AssociaPv datastruktur •  Indexerad med nycklar –  nyckel -­‐ värde par •  Snabb access Pll nycklar/värden Lund University / Lunarc / Python Lecture 1 DicPonaries >>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098} >>> tel['jack'] 4098 >>> del tel['sape'] >>> tel['irv'] = 4127 >>> tel {'guido': 4127, 'irv': 4127, 'jack': 4098} >>> tel.keys() ['guido', 'irv', 'jack'] >>> tel.has_key('guido') True Lund University / Lunarc / Python Lecture 1 Loop-­‐tekniker >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print k, v ... gallahad the pure robin the brave >>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print i, v ... 0 tic 1 tac 2 toe Lund University / Lunarc / Python Lecture 1 Moduler •  Vid större projekt måste källkoden delas upp •  Modul = separat python-­‐script fil (.py-­‐fil) •  importeras genom import –  gör alla funkPoner i modulen Pllgängliga Lund University / Lunarc / Python Lecture 1 Moduler fibo.py
# Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result >>> import fibo >>> fibo.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibo.fib2(100) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] >>> fibo.__name__ 'fibo' Lund University / Lunarc / Python Lecture 1 Moduler >>> from fibo import fib, fib2 >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 >>> from fibo import * >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 Lund University / Lunarc / Python Lecture 1 In-­‐ och utdatahantering Lund University / Lunarc / Python Lecture 1 Formaterad utskriY Formatkoder >>> for x in range(1,11): ... print '%2d %3d %4d' % (x, x*x, x*x*x) ... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 Lund University / Lunarc / Python Lecture 1 Formatkoder %d %5d %-­‐5d %05d %g %e %11.3e
%5.1f
%.3f %s %-­‐20s : integer : integer in a field of width 5 chars : integer in a field of width 5 chars, but adjusted to the left : integer in a field of width 5 chars, padded with zeroes from the left : float variable in %f or %g notation : float variable in scientific notation : float variable in scientific notation, with 3 decimals, field of width 11 chars : float variable in fixed decimal notation, with one decimal, field of width 5 chars : float variable in fixed decimal form, with three decimals, field of min. width : string : string in a field of width 20 chars, and adjusted to the left Lund University / Lunarc / Python Lecture 1 UtskriY forts. Önskad utdata Hello, World! sin(3.4)=-­‐0.255541102027 # Sammanfogning av strängar print "Hello, World! sin(" + str(r) + ")=" + str(s) # printf-­‐satser: print "Hello, World! sin(%g)=%g" % (r,s) # Variabel interpolation: print "Hello, World! sin(%(r)g)=%(s)g" % vars() Lund University / Lunarc / Python Lecture 1 Filhantering •  Öppna filer ifile = open( infilename, ’r’) # r for reading ofile = open(outfilename, ’w’) # w for writing afile = open(appfilename, ’a’) # a for appending •  Läsa rad för rad for line in ifile: # process line Lund University / Lunarc / Python Lecture 1 Filhantering •  Läsa in en hel fil (lista av strängar): infile = open(’data1.txt’, ’r’) lines = infile.readlines() # ekvivalent med lines = [] for line in infile: lines.append(line) •  Läsa in en hel fil som en sträng: filestr = infile.read() Lund University / Lunarc / Python Lecture 1 Konvertering av värden Pll fly@al infile = open("numbers.txt", "r") for line in infile: words = line.split() numbers = [float(w) for w in words] print numbers [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] [7.0, 8.0, 9.0] [10.0, 11.0, 12.0, 13.0] Lund University / Lunarc / Python Lecture 1 numbers.txt 1 2 3 4 5 6 7 8 9 10 11 12 13 Skriva Pll fil outfile = open(”outfile.txt”, ”w”) Ny rad for i in range(10): outfile.write(”%d\n” % i) [email protected] outfile.close() 0 1 2 3 4 5 6 7 8 9 Lund University / Lunarc / Python Lecture 1 Numpy and f2py Lund University / Lunarc / Python Lecture 1 Numpy •  Python extensions for manipulaPng large sets of objects organised in a grid-­‐like fashion –  Vectors –  Matrices –  etc... •  Normal Python datastructures too slow Lund University / Lunarc / Python Lecture 1 Using Numpy >>> from numpy import * >>> Lund University / Lunarc / Python Lecture 1 Array objects •  Homogeneous collecPon of large numbers of numbers –  Numbers of the same type –  Array objects must be full –  Size immutable –  Numbers can change •  size = total number of elements in the array (Does not change) •  shape = number of dimensions Lund University / Lunarc / Python Lecture 1 Array objects •  rank = len(shape) •  typecode = single character idenPfying the element kind –  Number format (i, d etc) –  Character –  Python reference •  itemsize = number 8-­‐bit bytes represenPng a single element Lund University / Lunarc / Python Lecture 1 CreaPng arrays from scratch >>> a = array([1, 3, 5], float) >>> print a [ 1. 3. 5.] >>> b = array([5,4,3], int) >>> print b [5 4 3] >>> c = array([1.0,1.5,3.0]) >>> print c [ 1. 1.5 3. ] >>> d = array([1,2,4,5,6]) >>> print d [1 2 4 5 6] Lund University / Lunarc / Python Lecture 1 Explicit typecode Implicit typecode MulPdimensional arrays >>> a = array([[1,2],[3,4]]) >>> print a [[1 2] [3 4]] >>> b = array([[1,2,3,4],[5,6,7,8]], Float) >>> print b [[ 1. 2. 3. 4.] [ 5. 6. 7. 8.]] >>> print a.shape (2, 2) >>> print b.shape (2, 4) Lund University / Lunarc / Python Lecture 1 Reshaping >>> print a [[1 2] [3 4]] >>> a_flat = reshape(a, [4,]) >>> print a_flat [1 2 3 4] >>> print b [[ 1. 2. 3. 4.] [ 5. 6. 7. 8.]] >>> b_shaped = reshape(b, [8,]) >>> print b_shaped [ 1. 2. 3. 4. 5. 6. 7. 8.] >>> b_shaped = reshape(b, [4,2]) >>> print b_shaped [[ 1. 2.] [ 3. 4.] [ 5. 6.] [ 7. 8.]] ≠
Lund University / Lunarc / Python Lecture 1 >>> b array([[ 1., 2., 3., 4.], [ 5., 6., 7., 8.]]) >>> b_trans = transpose(b) >>> print b_trans [[ 1. 5.] [ 2. 6.] [ 3. 7.] [ 4. 8.]] Growing an array >>> a = array([1,2]) >>> b = array([a,a]) >>> b array([[1, 2], [1, 2]]) Lund University / Lunarc / Python Lecture 1 >>> base = array([[1,2],[3,4]]) >>> big = resize(base, [9,9]) >>> print big [[1 2 3 4 1 2 3 4 1] [2 3 4 1 2 3 4 1 2] [3 4 1 2 3 4 1 2 3] [4 1 2 3 4 1 2 3 4] [1 2 3 4 1 2 3 4 1] [2 3 4 1 2 3 4 1 2] [3 4 1 2 3 4 1 2 3] [4 1 2 3 4 1 2 3 4] [1 2 3 4 1 2 3 4 1]] >>> big = resize(base, [4,4]) >>> print big [[1 2 3 4] [1 2 3 4] [1 2 3 4] [1 2 3 4]] >>> big = resize(base, [4,2]) >>> print big [[1 2] [3 4] [1 2] [3 4]] Arrays on the fly >>> a = zeros([4,4]) >>> print a [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] >>> b = ones([5,10],Float) >>> print b [[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]] Lund University / Lunarc / Python Lecture 1 Arrays on the fly >>> a = arange(10) >>> print a [0 1 2 3 4 5 6 7 8 9] Lund University / Lunarc / Python Lecture 1 >>> b = reshape(range(100), [10,10]) >>> print b [[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39] [40 41 42 43 44 45 46 47 48 49] [50 51 52 53 54 55 56 57 58 59] [60 61 62 63 64 65 66 67 68 69] [70 71 72 73 74 75 76 77 78 79] [80 81 82 83 84 85 86 87 88 89] [90 91 92 93 94 95 96 97 98 99]] Arrays on the fly >>> a = arange(0,10) >>> print a [0 1 2 3 4 5 6 7 8 9] >>> a = arange(-­‐10,10) >>> print a [-­‐10 -­‐9 -­‐8 -­‐7 -­‐6 -­‐5 -­‐4 -­‐3 -­‐2 -­‐1 0 1 2 3 4 5 6 7 8 9] >>> a = arange(-­‐10,10,2) >>> print a [-­‐10 -­‐8 -­‐6 -­‐4 -­‐2 0 2 4 6 8] Lund University / Lunarc / Python Lecture 1 Arrays on the fly >>> a = array([[42]*5]*5) >>> print a [[42 42 42 42 42] [42 42 42 42 42] [42 42 42 42 42] [42 42 42 42 42] [42 42 42 42 42]] Slow
>>> a = zeros([5,5])+42 >>> print a [[42 42 42 42 42] [42 42 42 42 42] [42 42 42 42 42] [42 42 42 42 42] [42 42 42 42 42]] Fast
Lund University / Lunarc / Python Lecture 1 Arrays on the fly >>> i = identity(10) >>> print i [[1 0 0 0 0 0 0 0 0 0] [0 1 0 0 0 0 0 0 0 0] [0 0 1 0 0 0 0 0 0 0] [0 0 0 1 0 0 0 0 0 0] [0 0 0 0 1 0 0 0 0 0] [0 0 0 0 0 1 0 0 0 0] [0 0 0 0 0 0 1 0 0 0] [0 0 0 0 0 0 0 1 0 0] [0 0 0 0 0 0 0 0 1 0] [0 0 0 0 0 0 0 0 0 1]] Lund University / Lunarc / Python Lecture 1 Array av värden inom linjärt interval x = linspace(0.0, 1.0, 10) print x [ 0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556 0.66666667 0.77777778 0.88888889 1. ] Lund University / Lunarc / Python Lecture 1 OperaPng on arrays >>> a = array([[1,2],[3,4]]) >>> print a [[1 2] [3 4]] >>> print a + 3 [[4 5] [6 7]] >>> print a * 3 [[ 3 6] [ 9 12]] Lund University / Lunarc / Python Lecture 1 >>> print sin(a) [[ 0.84147098 0.90929743] [ 0.14112001 -­‐0.7568025 ]] >>> print -­‐a [[-­‐1 -­‐2] [-­‐3 -­‐4]] >>> print a + a [[2 4] [6 8]] OperaPng on arrays >>> a = [1,2,3] >>> b = ones([5,3]) >>> print a [1, 2, 3] >>> print b [[1 1 1] [1 1 1] [1 1 1] [1 1 1] [1 1 1]] >>> print a + b [[2 3 4] [2 3 4] [2 3 4] [2 3 4] [2 3 4]] Lund University / Lunarc / Python Lecture 1 Gelng and selng values >>> a = arange(10) >>> print a [0 1 2 3 4 5 6 7 8 9] >>> print a[0] 0 >>> print a[1:5] [1 2 3 4] >>> print a[-­‐1] 9 >>> print a[:-­‐1] [0 1 2 3 4 5 6 7 8] Lund University / Lunarc / Python Lecture 1 >>> a = arange(16) + 1 >>> reshape(a,[4,4]) array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) >>> a = reshape(a,[4,4]) >>> print a [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] >>> print a[0] [1 2 3 4] >>> print a[0,0] 1 >>> print a[-­‐1] [13 14 15 16] Gelng and selng values >>> print a [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] >>> a[0,0] = 42 >>> print a [[42 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] >>> a[1] = [42, 42, 42, 42] >>> print a [[42 2 3 4] [42 42 42 42] [ 9 10 11 12] [13 14 15 16]] Lund University / Lunarc / Python Lecture 1 Slicing >>> a = reshape(arange(16)+1,[4,4]) >>> print a [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] >>> print a[:,:] [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] >>> print a[:,1] [ 2 6 10 14] >>> print a[1,:] [5 6 7 8] Lund University / Lunarc / Python Lecture 1 Ufuncs • 
• 
• 
• 
• 
Operates elementwise on arrays Available as callable objects (funcPons) Can operate on Python sequences Can take output arguments Have special methods Lund University / Lunarc / Python Lecture 1 Ufuncs >>> a = arange(10) >>> print a [0 1 2 3 4 5 6 7 8 9] >>> print add(a,a) [ 0 2 4 6 8 10 12 14 16 18] >>> print a + a [ 0 2 4 6 8 10 12 14 16 18] >>> print sin(a) [ 0. 0.84147098 0.90929743 0.14112001 -­‐0.7568025 -­‐0.95892427 -­‐0.2794155 0.6569866 0.98935825 0.41211849] >>> print add(a, range(10)) [ 0 2 4 6 8 10 12 14 16 18] Lund University / Lunarc / Python Lecture 1 Ufuncs Copy >>> a = arange(10) >>> a = a * 10 >>> print a [ 0 10 20 30 40 50 60 70 80 90] >>> a = arange(10) >>> multiply(a,10,a) >>> print a [ 0 10 20 30 40 50 60 70 80 90] Lund University / Lunarc / Python Lecture 1 Ufuncs reduce >>> a = arange(10) >>> print a [0 1 2 3 4 5 6 7 8 9] >>> print add.reduce(a) 45 >>> a = reshape(arange(16),[4,4]) >>> print a [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] >>> print add.reduce(a) [24 28 32 36] >>> print add.reduce(a,1) [ 6 22 38 54] Lund University / Lunarc / Python Lecture 1 Ufuncs accumulate >>> a = arange(10) >>> print a [0 1 2 3 4 5 6 7 8 9] >>> print add.accumulate(a) [ 0 1 3 6 10 15 21 28 36 45] Lund University / Lunarc / Python Lecture 1 Array funcPon take >>> a = reshape(arange(16),[4,4]) >>> print a [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] >>> print take(a,[0,],1) [12 13 14 15]] [[ 0] >>> print take(a,[0,]) [ 4] [ [0 1 2 3]] [ 8] >>> print take(a,[0,1]) [12]] [[0 1 2 3] >>> print take(a,[0,1],1) [4 5 6 7]] [[ 0 1] >>> print take(a,[0,-­‐1]) [ 4 5] [[ 0 1 2 3] [ 8 9] [12 13 14 15]] [12 13]] >>> print take(a,[0,-­‐1],1) [[ 0 3] [ 4 7] [ 8 11] [12 15]] Lund University / Lunarc / Python Lecture 1 Array funcPon put >>> a = arange(6) >>> print a [0 1 2 3 4 5] >>> put(a, [0,2,4], [42,42,42]) >>> print a [42 1 42 3 42 5] Lund University / Lunarc / Python Lecture 1 >>> a = reshape(arange(16), [4,4]) >>> print a [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] >>> put(a, [0,3,12,15], [42,42,42,42]) >>> print a [[42 1 2 42] [ 4 5 6 7] [ 8 9 10 11] [42 13 14 42]] Array funcPon transpose >>> a = reshape(arange(16), [4,4]) >>> print a [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] >>> print transpose(a) [[ 0 4 8 12] [ 1 5 9 13] [ 2 6 10 14] [ 3 7 11 15]] Lund University / Lunarc / Python Lecture 1 Array funcPon diagonal, trace >>> print a [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] >>> print diagonal(a) [ 0 5 10 15] >>> print trace(a) 30 >>> print diagonal(a,1) [ 1 6 11] >>> print trace(a,1) 18 Lund University / Lunarc / Python Lecture 1 Array funcPon matrixmulPply >>> print a [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] >>> print matrixmultiply(a,a) [[ 56 62 68 74] [152 174 196 218] [248 286 324 362] [344 398 452 506]] Lund University / Lunarc / Python Lecture 1 Vektor exempel 1 from math import * from numpy import * a = zeros(20) print a x = linspace(0.0, 2.0*pi, 20) y = sin(x) print x [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. print y 0. 0.] [ 0. 0.33069396 0.66138793 0.99208189 1.32277585 1.65346982 1.98416378 2.31485774 2.64555171 2.97624567 3.30693964 3.6376336 3.96832756 4.29902153 4.62971549 4.96040945 5.29110342 5.62179738 5.95249134 6.28318531] [ 0.00000000e+00 3.24699469e-­‐01 6.14212713e-­‐01 8.37166478e-­‐01 9.69400266e-­‐01 9.96584493e-­‐01 9.15773327e-­‐01 7.35723911e-­‐01 4.75947393e-­‐01 1.64594590e-­‐01 -­‐1.64594590e-­‐01 -­‐4.75947393e-­‐01 -­‐7.35723911e-­‐01 -­‐9.15773327e-­‐01 -­‐9.96584493e-­‐01 -­‐9.69400266e-­‐01 -­‐8.37166478e-­‐01 -­‐6.14212713e-­‐01 -­‐3.24699469e-­‐01 -­‐2.44921271e-­‐16] Lund University / Lunarc / Python Lecture 1 Vektor exempel 2 from math import * from numpy import * from pylab import * x = linspace(0.0, 2.0*pi, 20) y = sin(x) plot(x,y) show() Lund University / Lunarc / Python Lecture 1 Matris exempel from numpy import * A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) x = matrix( [[1],[2],[3]] ) y = matrix( [[1,2,3]] ) print A.T print A*x print A.I print linalg.solve(A, x) [[ 1 11 21] [ 2 12 22] [ 3 13 23]] [[ 14] [ 74] [134]] [[ 2.81466387e+14 -­‐5.62932774e+14 2.81466387e+14] [ -­‐5.62932774e+14 1.12586555e+15 -­‐5.62932774e+14] [ 2.81466387e+14 -­‐5.62932774e+14 2.81466387e+14]] [[-­‐0.01430315] [-­‐0.6713937 ] [ 0.78569685]] Lund University / Lunarc / Python Lecture 1 Utvecklingsmiljön IDLE Lund University / Lunarc / Python Lecture 1 Huvudfönster Interak8v prompt Lund University / Lunarc / Python Lecture 1 Skapa en ny python-­‐fil Lund University / Lunarc / Python Lecture 1 Spara python-­‐fil Lund University / Lunarc / Python Lecture 1 Exekvera python-­‐fil Lund University / Lunarc / Python Lecture 1