#Examples for Week 3 import numpy as np ################################## #Basic if, elif, and else statements (remember these can be nested) x = 5 y = 4 z = 2*x + y if z < y: print 'This will never print.' print 'Something Else' elif z = y: z += 1 elif ((2*z < x**2) or y>x) and (3*z > y**2): print 'Wow!' else: print 'case 4' if x > y: print 'yay' elif x 5: print x x = x - 1 if timer > 20: x=0 ################################### #Iterating over a range, and checking it against the index of the list list1 = [1,56,2,6,3,5,2,6,8,19] for i in range(len(list1)): #Range(10) = [0,1,2,3,4,5,6,7,8,9] if i < 5: print list1[i] elif i > 5: print list1[i-1] print i**2 #################################### #Iterating over elements in a list/array arr = np.array([1.,5,7,4,2,9,76,4]) arr_2 = np.array([4,6,4,7,4,2]) for i in arr: print i**2 if i not in arr_2: print 'Not in array 2' elif i in arr_2: print 'Aw Yis' #Nested For Loop one = np.arange(100) two = np.ones(100)*25 empty_list = [] empty_array = np.array([]) for i in range(len(one)): for j in range(len(two)): if one[i]==two[j]: empty.append([i,j,one[i]]) #[12,45,2] np.append(empty_array, [i,j,one[i]]) ##################################### x = np.arange(10, 10, 2) y = np.sin(x) #input arr_like def avg(arr1,arr2): avg = (arr1 + arr2) / 2. return avg x1 = avg(arr1, array_2) def age_calc(birth_year): current = time.asctime( time.localtime(time.time()) ) current_year = current[-1:-4] age = current_year - birth_year return age my_age= age_calc(1994) cousin_age= age_calc(1975) def normalize(type, array): ''' A function to normalize arrays. INPUT: (type, array), where type is either "max1", "mean1", or "median1" OUTPUT: A normalized array ''' if type=='max1': new_array = array/np.max(array) elif type=='mean1': new_array = array/np.mean(array) elif type=='median1': new_array = array/np.median(array) return new_array spectrum = np.array([1,2,3,4,5,...,1,4,6,4,2]) #Not real, but could be some long spectrum normed_spectrum = normalize('median1', spectrum) normed_by_mean = normalize('mean1', spectrum) help(normalize) #####################################