Python for Scientific Computing: Dynamic Typing, Containers, Functions, and Scipy, Assignments of Physics

An introduction to python, focusing on its dynamic typing, built-in container types (tuples, dictionaries, and sets), functions, and the use of the scipy package for scientific computing. Python is a versatile and popular programming language for scientific and data-intensive applications. In this document, we cover the basics of python, including its dynamic typing, containers, and functions, as well as an overview of the scipy package for scientific computing.

Typology: Assignments

Pre 2010

Uploaded on 08/30/2009

koofers-user-2d5
koofers-user-2d5 🇺🇸

10 documents

1 / 32

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
An introduction to Python
and external packages for scientific computing
Phys 7682 / CIS 6229
Computational Methods for Nonlinear Systems
www.physics.cornell.edu/~myers/teaching/ComputationalMethods
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20

Partial preview of the text

Download Python for Scientific Computing: Dynamic Typing, Containers, Functions, and Scipy and more Assignments Physics in PDF only on Docsity!

An introduction to Python

and external packages for scientific computing

Phys 7682 / CIS 6229

Computational Methods for Nonlinear Systems

www.physics.cornell.edu/~myers/teaching/ComputationalMethods

  • Python is dynamically typed
    • (^) objects have types, but types of variables are not explicitly declared
    • (^) variable names are attached to objects by assignment ‣ x=3 # x is the integer 3; name x added to namespace ‣ x=3.0 # x is the floating point 3. ‣ x=’blah’ # x is the string ‘blah’ ‣ x=[3,3.0,’blah’] # x is a list with 3 elements ‣ x=3+3.0 # x is the floating point 6. ‣ x=3+‘blah’ # error: cannot add int and string
    • dynamic but strongly typed: only allowable operations can be executed Python (www.python.org)

Python is interpreted

individual statements are automatically compiled to bytecodes and executed within an interpreter

  • interpreters can run full Python programs without human interaction, or execute individual commands in an interactive mode
  • e.g., python myfile.py # runs myfile.py in python interpreter
  • e.g., in the ipython interpreter: In [1]: x = 3 In [2]: print x 3 In [3]: y = x + 4. In [4]: print y 7. ipython adds to the standard interpreter:
  • command history
  • command completion (TAB)
  • introspection and help
  • “magic” functions (e.g., %run)
  • streamlined access to operating system See IPython paper on course web site for more details.

Python is object-oriented (OO)

everything in Python is an object, i.e., a datatype with a defined set of

allowable functions or operations (“methods”)

methods (and other attributes) accessed via. (dot) operator

e.g., ‣ x = 3 # x is an integer ‣ y = x + 4 # addition def’d for ints by add method ‣ a = [1,2,3] # a is a list ‣ a.append(4) # append is a method on list type

but Python also allows for non-OO procedural code, e.g.,

def factorial(n):

code to implement factorial

factorial is an object of function type

x = factorial(3) # equiv. to factorial.call(3) y = x*x

character strings

s = ‘home’

  • t = ‘running’

  • w = s + t[0:3] # what is the value of w?

  • print ‘value of %s = %s’ % (name, val) # formatted string

  • s = “home” # strings via single or double quotes

  • doc = “””this string extends

  • over multiple lines”””

  • do not need to escape end-of-lines in triple-quoted strings

    Python Basics: Built-in Types

lists: ordered, dynamic, heterogeneous collections

a = [1,[2.1, ‘hello’],‘b’, True] ‣ indexing: a[0] is 1 ; a[1] is [2.1, ‘hello’]; 0-offset ‣ slicing: a[1:3] is [[2, ‘hello’],‘b’]

  • for element in a: # do something to every element
  • b = [1,2,3] + [4,5,6] # list addition is concatenation
  • a.reverse()
  • a.append(obj) # append obj to end of list in place
  • a.sort(comparison_func) # sort according to func
  • help(list) # get documentation, incl. defined methods Python Basics: Built-in Container Types

Python Basics: Containers (cont’d)

dictionaries: maps from keys to values (maps, associative arrays, hashes)

key can be any immutable type; value can be any type

  • d = {’a’: 1, ‘b’: 2}
  • d[’c’] = d[’a’] + d[’b’] # now d[’c’]=
  • d[(1, (2,3), 12, ‘x’)] = some_object
  • d.keys() # method returning list of keys (arbitrary order)
  • d.values() # method returning list of values (arb. order)
  • d.has_key(arg) # is arg a key in d?
  • method/attribute lookup on objects done via dictionaries ‣ e.g., a = [1,2,3]; a.append(4) ‣ looks for ‘append’ as key in list.dict ‣ a.append(4) calls list.dict’append’

Python Basics: Containers, etc.

sets: unordered collections of unique elements

s1 = set([1,2,3]); s2 = set([3,4,5])

  • s3 = s1 & s2 # returns intersection: set([3])
  • s3 = s1 - s2 # returns difference set([1,2])

file objects

output = open(’blah’, ‘w’)

  • output.write(’%6.3e\t%6.3e\n’ % (x, y))

function objects

def g(z):

code body and return statement for g(z)

  • f = lambda x: x + 3 # defines func f that returns arg+
  • functions called with () operator [ call() method ]

Python Basics: Built-in functions

built-in functions, e.g.,

help(obj): get help about an object

  • dir(obj): get list of attributes and methods defined on an object
  • range(N,M): return list of integers from N to M-
  • eval(string): evaluate a string as a Python expression ‣ eval(’Cx*n’, {’C’:10.,‘x’:2.0, ‘n’:3})
  • str(object): convert obj to its string representation
  • zip(seq1, seq2, ...): return “zipped” list of tuples ‣ e.g., zip([1,2,3],[4,5,6]) -> [(1,4), (2,5), (3,6)]
  • iter(collection): return iterator to traverse collection

Python Basics: Control flow (note role of code indentation)

for: iteration over a list (or any other iterable type)

for element in list:

do something to every element in list

for i in range(N):

i assumes values 0,1,2,...,N-1 (N elements in all)

if - elif - else:

if (x > 3) and (y < 4):

do something

elif y >= 4: # elif block not required

do something else

else: # else block not required

do something different still

Arguments to functions def g(x, y, z): # function g requires 3 arguments return x + 2y + 3z def f(x, y=3, z=10): # f defined with default arguments; requires 1 return x + 2y + 3z w = f(5) # w = 5 + 23 + 3 w = f(5, 20) # w = 5 + 220 + 3 w = f(3, 10, -2) # w = 3 + 210 - 3

Can specify arguments by keyword in any order:

w = f(z=8, y=0, x=2) # w = 2 + 20 + 3

Can bundle arguments into tuple and apply function to tuple

args = (10, 20, 30) w = f(*args) # w = f(args[0], args[1], args[2])

Functions & arguments (cont’d)

references to objects are passed “by reference” and bound to local

names in function scope

immutable arguments (e.g., numbers, strings) cannot be changed in function scope, so a local copy is made (passed “by value”)

  • mutable arguments (e.g., lists, dictionaries) can be changed within the function body since local variable and global variable can share the same reference

Example from Lutz, Learning Python (3rd ed), p. 327

def changer(x,y): # Function x = 2 # Changes local name’s value only y[0] = ‘spam’ # Changes shared object in place X = 1 L = [1,2] changer(X,L) # Pass immutable and mutable print X,L # (1, [‘spam’, 2])

OOP in Python (cont’d.)

make a ring graph with 10 nodes

g = UndirectedGraph() for i in range(10): g.AddEdge(i, (i+1)%10) # % is modulo operator

read data from a file of node pairs and make a graph

g = UndirectedGraph() for line in file(’graphdata.txt’): nodes = line.split() # split the line by whitespace g.AddEdge(nodes[0], nodes[1]) # nodes are strings in this graph g.AddEdge((i,j), (m,n)) # tuples as nodes (edges in a 2D lattice)

OOP in Python (cont’d.)

special methods can be defined for classes, e.g.,

  • init(self, ...): constructor / initialization
  • repr(self): how an object prints itself
  • add(self, other): add self to other: a + b
  • sub(self, other): subtract other from self: a - b
  • getitem(self, i): get ith element of object: x[i]
  • call(self, args): call object with args: f(x,y,z)