import numpy as np import pylab as pl # you can, but don't have to declare the type dave = 5 print dave, type(dave) # dynamically updated -- good/bad dave = 5. print dave, type(dave) dave = "David Lagattuta" print dave, type(dave) # a few string examples print "split example:", dave.split() print "join example:", '__'.join(dave.split()) # Bracket-types tell you about the "thing" it's storing dave = [2.3, 4.5, 6.9] print dave, type(dave) dave = [2.3, 4.5, 6.9, "hey there", 4] print dave, type(dave) dave = [2.3, 4.5, 6.9, "hey there", [2.1, 7.8], ] print dave, type(dave) eight_int = 8 five_int = 5 print "8/5 =", eight_int / five_int # Integer division five_float = 5.0 print "8/5.0 =", eight_int / five_float # changes everything blank_list = [] # how to create a blank list #add list comprehensions dave = [x**2 for x in xrange(5)] print dave, type(dave) from math import pi print [str(round(pi, i)) for i in xrange(2, 9)] # Unnecessarily complicated example to show off. print [(i, str(round(pi, i)), round(pi, i)) for i in xrange(2, 9)] tuple_example = ('Jonathan', 'Whitmore', 30, 'AR_building_rocks@wow.com') print tuple_example print type(tuple_example) first_name, last_name, age, email = tuple_example print last_name, first_name print age print email list_comp_example = [i**2 for i in xrange(10)] print list_comp_example print sum([i**2 for i in xrange(10)]) # Generator version! print sum(i**2 for i in xrange(10)) # TODO numpy # http://stackoverflow.com/questions/3394835/args-and-kwargs def print_everything(*args): for count, thing in enumerate(args): print '{0}. {1}'.format(count, thing) print_everything('apple', 'banana', 'cabbage') # Similarly, **kwargs allows you to handle named arguments that you have not defined in advance: def table_things(title_string, **kwargs): print title_string print "-" * len(title_string) for name, value in kwargs.items(): print '{0} = {1}'.format(name, value) table_things("Classifying stuff", apple = 'fruit', cabbage = 'vegetable') dave = "Hi there people! " print dave.startswith("hi ") print dave.splitlines() print dave.strip() jw = dave.split() [x for x in jw if x.startswith('p')] # You can import modules/subpackages as whatever name you want to call them. from scipy import ndimage as dave_sucks print numpy.arange(12) print numpy.arange(12) ** 2 print type(np.arange(12)) # python x = range(10000) %timeit [item + 1 for item in x] # numpy x = np.arange(10000) %timeit x + 1 print "x -> ", x # notice the smart printing print "x[:] -> ", x[:] print "x[0] -> ", x[0] # first element print "x[0:5] -> ", x[0:5] # first 5 elements print "x[-1] -> ", x[-1] # last element # A bit more complicated slicing print x[-5:] # last five elements print x[-5:-2] # print x[-5:-1] # last 4 elements (not final value) # create evenly spaced arrays print np.arange(5, 50, step=3, ) print np.linspace(5, 50, num=3, endpoint=True, ) print np.linspace(5, 50, num=3, endpoint=False, ) np.array([[x, x**2, x/2.0] for x in range(10)]) + 5 input_data = np.random.random(50) * 2 * np.pi response_data = np.sin(input_data) pl.plot(input_data, response_data) pl.scatter(input_data, response_data) index_order = input_data.argsort() index_order pl.plot(input_data[index_order], response_data[index_order]) # TODO: Explain this in some detail import cPickle as pickle test = np.arange(1e7) # This should take a bit with open('myjunkfile', 'w') as filehandle: pickle.dump(test, filehandle) with open('myjunkfile2','wb') as filehandle: pickle.dump(test, filehandle, protocol=-1) with open('myjunkfile2', 'rb') as filehandle: new_variable = pickle.load(test) mygenerator = (x**2 for x in range(3)) for item in mygenerator: print item for item in mygenerator: print item # Can't reuse w/o reloading them! # some from: http://stackoverflow.com/questions/101268/hidden-features-of-python?lq=1# # Chaining comparison operators x = 5 print 1 < x < 10 print 10 < x < 20 print 10 > x <= 9 print 5 == x > 4 ### Index slicing ### a = np.arange(12) a[::2] # reverse a[::-1] for x in reversed(a): print x print a[:] print a[0:] print a[-1] print a[-2] print a[1:-2] a = 10 b = 5 print a, b a, b = b, a print a, b x = 5 #y = 5 y = 1 x = 3 if (y == 1) else 2 print x # VECTORIZE def test(a,b): if a>b: return a else: return b print test(10,-3) print test(-5,-3) #x = np.array(r_[-10:10:2]) x = np.arange(-10,10.1,2) y = np.ones(x.shape)*-3. print test(x,y) # error #long way out = np.empty(x.shape) for i in range(x.size): out[i] = test(x[i],y[i]) print out #short way vtest = np.vectorize(test) print vtest(x,3) out = vtest(x,y) print out import itertools def coolguys(name): if (name == 'David')|(name=='Spider Man'): return 'cool' else: return 'lame' guys = np.array(['David','Jonathan', 'Fred','Bob','Steve','Spider Man']) vcool = vectorize(coolguys) #vectorize the function, for simplicity results = vcool(guys) for guy, result in itertools.izip(guys, results): print guy, "is", result coolness = {'name':guys, 'status':results} #turn the results into a dictionary # save dictionary to a pickle for later use with open('whoiscool','w') as ff: pickle.dump(coolness,ff) with open('whoiscool') as fnew: data = pickle.load(fnew) print data # Notice this is the data structure as saved!