├── README.md ├── Week0-The_Function_and_the_Field ├── Inverse_Index_Lab │ ├── dictutil.py │ ├── inverse_index_lab.pdf │ ├── inverse_index_lab.py │ ├── inverse_index_lab_git.py │ ├── stories_big.txt │ └── stories_small.txt ├── Python_Lab │ ├── python_lab.pdf │ └── python_lab.py ├── The_Field_Problems │ ├── GF2.py │ ├── The_Field_problems.pdf │ ├── The_Field_problems.py │ ├── image.py │ ├── img01.png │ ├── plotting.py │ └── png.py └── The_Function_Problems │ ├── The_Function_problems.pdf │ └── The_Function_problems.py ├── Week1-The_Vector ├── Politics_Lab │ ├── UN_voting_data.txt │ ├── US_Senate_voting_data_109.txt │ ├── politics_lab.pdf │ ├── politics_lab.py │ └── voting_record_dump109.txt ├── The_Vector_Problems │ ├── The_Vector_problems.pdf │ └── The_Vector_problems.py └── Vector_Class_Homework │ ├── vec.pdf │ └── vec.py ├── Week2-The_Vector_Space ├── The_Vector_Space_Problems │ ├── The_Vector_Space_problems.pdf │ ├── The_Vector_Space_problems.py │ ├── vec.py │ └── vecutil.py ├── coursera_submit.py └── profile.txt ├── Week3-The_Matrix ├── Error_Correcting_Code_Lab │ ├── bitutil.py │ ├── ecc_lab.pdf │ ├── ecc_lab.py │ ├── mat.py │ ├── matutil.py │ └── vec.py ├── Matrix_Class_Homework │ ├── mat.pdf │ ├── mat.py │ └── mat_sparsity.py └── The_Matrix_Problems │ ├── The_Matrix_problems.pdf │ ├── The_Matrix_problems.py │ ├── UN_voting_data.txt │ ├── mat.py │ ├── matutil.py │ ├── solver.py │ └── vec.py ├── Week4-The_Basis ├── Geometry_Lab │ ├── geometry_lab.pdf │ ├── geometry_lab.py │ ├── image_mat_util.py │ ├── mat.py │ ├── png.py │ └── vec.py └── The_Basis_Problems │ ├── The_Basis_problems.pdf │ ├── The_Basis_problems.py │ ├── mat.py │ ├── matutil.py │ ├── solver.py │ └── vec.py ├── Week5-Dimension ├── Dimension_Problems │ ├── Dimension_problems.pdf │ ├── Dimension_problems.py │ ├── independence.py │ ├── mat.py │ ├── solver.py │ ├── triangular.py │ └── vec.py └── Perspective_Lab │ ├── board.png │ ├── cit.png │ ├── image_mat_util.py │ ├── mat.py │ ├── perspective_lab.pdf │ ├── perspective_lab.py │ ├── png.py │ └── vec.py ├── Week6-Gaussian_Elimination_and_the_Inner_Product ├── Gaussian_Elimination_Problems │ ├── Gaussian_Elimination_problems.pdf │ ├── Gaussian_Elimination_problems.py │ ├── cracking_rand.py │ ├── echelon.py │ ├── gaussian_examples.py │ ├── mat.py │ └── vec.py ├── Integer_Factoring_Lab │ ├── factoring_lab.pdf │ ├── factoring_lab.py │ ├── factoring_support.py │ ├── mat.py │ └── vec.py ├── Secret_Sharing_Lab │ ├── bitutil.py │ ├── cracking_rand.py │ ├── echelon.py │ ├── gaussian_examples.py │ ├── mat.py │ ├── secret_sharing_lab.pdf │ ├── secret_sharing_lab.py │ └── vec.py └── The_Inner_Product_Problems │ ├── The_Inner_Product_problems.pdf │ ├── The_Inner_Product_problems.py │ ├── mat.py │ ├── orthogonalization.py │ └── vec.py ├── Week7-Orthogonalization ├── Machine_Learning_Lab │ ├── cancer_data.py │ ├── machine_learning_lab.pdf │ ├── machine_learning_lab.py │ ├── mat.py │ ├── orthogonalization.py │ ├── train.data │ ├── validate.data │ └── vec.py └── Orthogonalization_Problems │ ├── GF2.py │ ├── Orthogonalization_problems.pdf │ ├── Orthogonalization_problems.py │ ├── Orthogonalization_problems.py.bak │ ├── QR.py │ ├── age-height.txt │ ├── bitutil.py │ ├── cancer_data.py │ ├── coursera_submit.py │ ├── dictutil.py │ ├── echelon.py │ ├── independence.py │ ├── machine_learning_lab.pdf │ ├── machine_learning_lab.py │ ├── mat.py │ ├── matutil.py │ ├── orthogonalization.py │ ├── python_lab.py │ ├── read_data.py │ ├── solver.py │ ├── train.data │ ├── triangular.py │ ├── validate.data │ ├── vec.py │ └── vecutil.py └── coursera_submit.py /README.md: -------------------------------------------------------------------------------- 1 | # Coding-the-Matrix 2 | This is a Coursera course, Coding the Matrix: Linear Algebra through Computer Science Applications by Philip Klein of Brown University. 3 | 4 | The cousrse id is matrix-002, 2015. Here are the Programing Assignments of the course.I hope you can do it by yourself. 5 | -------------------------------------------------------------------------------- /Week0-The_Function_and_the_Field/Inverse_Index_Lab/dictutil.py: -------------------------------------------------------------------------------- 1 | # Copyright 2013 Philip N. Klein 2 | def dict2list(dct, keylist): return [ dct[i] for i in keylist ]¬ 3 | def list2dict(L, keylist): return { keylist[i]:L[i] for i in range(len(L)) } 4 | -------------------------------------------------------------------------------- /Week0-The_Function_and_the_Field/Inverse_Index_Lab/inverse_index_lab.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codewatson/Coding-the-Matrix/4c855dc14d3df842336f796092c3664097a6bc03/Week0-The_Function_and_the_Field/Inverse_Index_Lab/inverse_index_lab.pdf -------------------------------------------------------------------------------- /Week0-The_Function_and_the_Field/Inverse_Index_Lab/inverse_index_lab.py: -------------------------------------------------------------------------------- 1 | from random import randint # version code d345910f07ae 2 | coursera = 1 3 | # Please fill out this stencil and submit using the provided submission script. 4 | 5 | 6 | 7 | 8 | 9 | ## 1: (Task 1) Movie Review 10 | ## Task 1 11 | def movie_review(name): 12 | """ 13 | Input: the name of a movie 14 | Output: a string (one of the review options), selected at random using randint 15 | """ 16 | movie_reviews=['See it!', 'A gem!', 'Ideological claptrapl!'] 17 | return movie_reviews[randint(0, len(movie_reviews)-1)] 18 | 19 | 20 | 21 | 22 | ## 2: (Task 2) Make Inverse Index 23 | def makeInverseIndex(strlist): 24 | """ 25 | Input: a list of documents as strings 26 | Output: a dictionary that maps each word in any document to the set consisting of the 27 | document ids (ie, the index in the strlist) for all documents containing the word. 28 | Distinguish between an occurence of a string (e.g. "use") in the document as a word 29 | (surrounded by spaces), and an occurence of the string as a substring of a word (e.g. "because"). 30 | Only the former should be represented in the inverse index. 31 | Feel free to use a loop instead of a comprehension. 32 | 33 | Example: 34 | >>> makeInverseIndex(['hello world','hello','hello cat','hellolot of cats']) == {'hello': {0, 1, 2}, 'cat': {2}, 'of': {3}, 'world': {0}, 'cats': {3}, 'hellolot': {3}} 35 | True 36 | """ 37 | words=set() 38 | tmpsets={} 39 | for tmplist in strlist: 40 | words |= set(tmplist.split()) 41 | for w in words: 42 | tmpsetsVal=set() 43 | for i in range(len(strlist)): 44 | if w in strlist[i] and w in strlist[i].split(): 45 | tmpsetsVal |= {i} 46 | tmpsets[w] = set(tmpsetsVal) 47 | 48 | return tmpsets 49 | 50 | ## 3: (Task 3) Or Search 51 | def orSearch(inverseIndex, query): 52 | """ 53 | Input: an inverse index, as created by makeInverseIndex, and a list of words to query 54 | Output: the set of document ids that contain _any_ of the specified words 55 | Feel free to use a loop instead of a comprehension. 56 | >>> idx = makeInverseIndex(['Johann Sebastian Bach', 'Johannes Brahms', 'Johann Strauss the Younger', 'Johann Strauss the Elder', ' Johann Christian Bach', 'Carl Philipp Emanuel Bach']) 57 | >>> orSearch(idx, ['Bach','the']) 58 | {0, 2, 3, 4, 5} 59 | >>> orSearch(idx, ['Johann', 'Carl']) 60 | {0, 2, 3, 4, 5} 61 | """ 62 | qSets=set() 63 | for i in range(len(query)): 64 | if query[i] in list(inverseIndex.keys()): 65 | qSets |= inverseIndex[query[i]] 66 | return qSets 67 | 68 | ## 4: (Task 4) And Search 69 | def andSearch(inverseIndex, query): 70 | """ 71 | Input: an inverse index, as created by makeInverseIndex, and a list of words to query 72 | Output: the set of all document ids that contain _all_ of the specified words 73 | Feel free to use a loop instead of a comprehension. 74 | 75 | >>> idx = makeInverseIndex(['Johann Sebastian Bach', 'Johannes Brahms', 'Johann Strauss the Younger', 'Johann Strauss the Elder', ' Johann Christian Bach', 'Carl Philipp Emanuel Bach']) 76 | >>> andSearch(idx, ['Johann', 'the']) 77 | {2, 3} 78 | >>> andSearch(idx, ['Johann', 'Bach']) 79 | {0, 4} 80 | """ 81 | qSets=set(range(len(inverseIndex))) 82 | for i in range(len(query)): 83 | if query[i] in list(inverseIndex.keys()): 84 | qSets &= inverseIndex[query[i]] 85 | return qSets 86 | 87 | -------------------------------------------------------------------------------- /Week0-The_Function_and_the_Field/Inverse_Index_Lab/inverse_index_lab_git.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | from dictutil import * 3 | 4 | ## Task 1 5 | def movie_review(name): 6 | """ 7 | Input: the name of a movie 8 | Output: a string (one of the review options), selected at random using randint 9 | """ 10 | review_options = ["See it!", "A gem!", "Ideological claptrap!"] 11 | return review_options[randint(0,len(review_options)-1)] 12 | 13 | ## Tasks 2 and 3 are in dictutil.py 14 | 15 | ## Task 4 16 | def makeInverseIndex(strlist): 17 | """ 18 | Input: a list of documents as strings 19 | Output: a dictionary that maps each word in any document to the set consisting of the 20 | document ids (ie, the index in the strlist) for all documents containing the word. 21 | Note that to test your function, you are welcome to use the files stories_small.txt 22 | or stories_big.txt included in the download. 23 | """ 24 | dict_inversed = {} 25 | for i in range(len(strlist)): 26 | strlist[i] = strlist[i].split() 27 | for j in range(len(strlist[i])): 28 | if strlist[i][j] not in dict_inversed: 29 | dict_inversed[strlist[i][j]] = {i} 30 | else: 31 | dict_inversed[strlist[i][j]] |= {i} 32 | return dict_inversed 33 | 34 | ## Task 5 35 | def orSearch(inverseIndex, query): 36 | """ 37 | Input: an inverse index, as created by makeInverseIndex, and a list of words to query 38 | Output: the set of document ids that contain _any_ of the specified words 39 | """ 40 | result = set() 41 | result |= inverseIndex[query[0]] 42 | for i in range(1, len(query)): 43 | result |= inverseIndex[query[i]] 44 | return result 45 | 46 | ## Task 6 47 | def andSearch(inverseIndex, query): 48 | """ 49 | Input: an inverse index, as created by makeInverseIndex, and a list of words to query 50 | Output: the set of all document ids that contain _all_ of the specified words 51 | """ 52 | result = set() 53 | result |= inverseIndex[query[0]] 54 | for i in range(1, len(query)): 55 | result &= inverseIndex[query[i]] 56 | return result -------------------------------------------------------------------------------- /Week0-The_Function_and_the_Field/Python_Lab/python_lab.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codewatson/Coding-the-Matrix/4c855dc14d3df842336f796092c3664097a6bc03/Week0-The_Function_and_the_Field/Python_Lab/python_lab.pdf -------------------------------------------------------------------------------- /Week0-The_Function_and_the_Field/Python_Lab/python_lab.py: -------------------------------------------------------------------------------- 1 | # version code a212a0defa59+ 2 | coursera = 1 3 | # Please fill out this stencil and submit using the provided submission script. 4 | 5 | 6 | 7 | 8 | 9 | ## 1: (Task 1) Minutes in a Week 10 | minutes_in_week = 60*24*7 11 | 12 | 13 | 14 | ## 2: (Task 2) Remainder 15 | remainder_without_mod = 2304811 - 2304811//47 *47 16 | 17 | 18 | 19 | ## 3: (Task 3) Divisibility 20 | divisible_by_3 = (673 % 3 == 0) and (909 % 3 == 0) 21 | 22 | 23 | 24 | ## 4: (Task 4) Conditional Expression 25 | x = -9 26 | y = 1/2 27 | expression_val = 2**(y+1/2) if x+10<0 else 2**(y-1/2) 28 | 29 | 30 | 31 | ## 5: (Task 5) Squares Set Comprehension 32 | first_five_squares = { x**2 for x in {1,2,3,4,5} } 33 | 34 | 35 | 36 | ## 6: (Task 6) Powers-of-2 Set Comprehension 37 | first_five_pows_two = { 2**x for x in {0,1,2,3,4} } 38 | 39 | 40 | 41 | ## 7: (Task 7) Double comprehension evaluating to nine-element set 42 | X1 = {1, 2, 3 } 43 | Y1 = { 5, 6 ,7} 44 | 45 | 46 | 47 | ## 8: (Task 8) Double comprehension evaluating to five-element set 48 | X2 = {1, 2, 4 } 49 | Y2 = {0, 8, 16 } 50 | 51 | 52 | 53 | ## 9: (Task 9) Set intersection as a comprehension 54 | S = {1, 2, 3, 4} 55 | T = {3, 4, 5, 6} 56 | # Replace { ... } with a one-line set comprehension that evaluates to the intersection of S and T 57 | S_intersect_T = { x for x in S if x in S and x in T } 58 | 59 | 60 | 61 | ## 10: (Task 10) Average 62 | list_of_numbers = [20, 10, 15, 75] 63 | # Replace ... with a one-line expression that evaluates to the average of list_of_numbers. 64 | # Your expression should refer to the variable list_of_numbers, and should work 65 | # for a list of any length greater than zero. 66 | list_average = sum(list_of_numbers) / len(list_of_numbers) 67 | 68 | 69 | 70 | ## 11: (Task 11) Cartesian-product comprehension 71 | # Replace ... with a double list comprehension over ['A','B','C'] and [1,2,3] 72 | cartesian_product = [ [x, y] for x in ['A','B','C'] for y in [1,2,3] ] 73 | 74 | 75 | 76 | ## 12: (Task 12) Sum of numbers in list of list of numbers 77 | LofL = [[.25, .75, .1], [-1, 0], [4, 4, 4, 4]] 78 | # Replace ... with a one-line expression of the form sum([sum(...) ... ]) that 79 | # includes a comprehension and evaluates to the sum of all numbers in all the lists. 80 | LofL_sum = sum([sum(x) for x in LofL]) 81 | 82 | 83 | 84 | ## 13: (Task 13) Three-element tuples summing to zero 85 | S = {-4, -2, 1, 2, 5, 0} 86 | # Replace [ ... ] with a one-line list comprehension in which S appears 87 | zero_sum_list = [ (i,j,k) for i in S for j in S for k in S if i+j+k == 0 ] 88 | 89 | 90 | 91 | ## 14: (Task 14) Nontrivial three-element tuples summing to zero 92 | S = {-4, -2, 1, 2, 5, 0} 93 | # Replace [ ... ] with a one-line list comprehension in which S appears 94 | exclude_zero_list = [ (i,j,k) for i in S for j in S for k in S if i+j+k == 0 if i != 0 or j !=0 or k != 0] 95 | 96 | 97 | 98 | ## 15: (Task 15) One nontrivial three-element tuple summing to zero 99 | S = {-4, -2, 1, 2, 5, 0} 100 | # Replace ... with a one-line expression that uses a list comprehension in which S appears 101 | first_of_tuples_list = [ (i,j,k) for i in S for j in S for k in S if i+j+k == 0 if i != j if j != k ][0] 102 | 103 | 104 | ## 16: (Task 16) List and set differ 105 | # Assign to example_L a list such that len(example_L) != len(list(set(example_L))) 106 | example_L = [0, 0, 1,2,3] 107 | 108 | 109 | 110 | ## 17: (Task 17) Odd numbers 111 | # Replace {...} with a one-line set comprehension over a range of the form range(n) 112 | odd_num_list_range = { i for i in range(100) if i % 2 == 1 } 113 | 114 | 115 | 116 | ## 18: (Task 18) Using range and zip 117 | # In the line below, replace ... with an expression that does not include a comprehension. 118 | # Instead, it should use zip and range. 119 | # Note: zip() does not return a list. It returns an 'iterator of tuples' 120 | L = ['A','B','C','D','E'] 121 | #range_and_zip = [(a, b) for (a, b) in zip(range(5), L) ] 122 | range_and_zip = list(zip(range(len(L)), L)) 123 | 124 | 125 | 126 | ## 19: (Task 19) Using zip to find elementwise sums 127 | A = [10, 25, 40] 128 | B = [1, 15, 20] 129 | # Replace [...] with a one-line comprehension that uses zip together with the variables A and B. 130 | # The comprehension should evaluate to a list whose ith element is the ith element of 131 | # A plus the ith element of B. 132 | list_sum_zip = [ sum(i) for i in zip(A,B) ] 133 | 134 | 135 | 136 | ## 20: (Task 20) Extracting the value corresponding to key k from each dictionary in a list 137 | dlist = [{'James':'Sean', 'director':'Terence'}, {'James':'Roger', 'director':'Lewis'}, {'James':'Pierce', 'director':'Roger'}] 138 | k = 'James' 139 | # Replace [...] with a one-line comprehension that uses dlist and k 140 | # and that evaluates to ['Sean','Roger','Pierce'] 141 | value_list = [ i[k] for i in dlist] 142 | 143 | 144 | 145 | ## 21: (Task 21) Extracting the value corresponding to k when it exists 146 | dlist = [{'Bilbo':'Ian','Frodo':'Elijah'},{'Bilbo':'Martin','Thorin':'Richard'}] 147 | k = 'Bilbo' 148 | #Replace [...] with a one-line comprehension 149 | value_list_modified_1 = [ i[k] if k in i else 'NOT PRESENT' for i in dlist ] # <-- Use the same expression here 150 | k = 'Frodo' 151 | value_list_modified_2 = [i.get(k,'NOT PRESENT') for i in dlist] # <-- as you do here 152 | 153 | 154 | 155 | ## 22: (Task 22) A dictionary mapping integers to their squares 156 | # Replace {...} with a one-line dictionary comprehension 157 | square_dict = { x:x*x for x in range(100) } 158 | 159 | 160 | 161 | ## 23: (Task 23) Making the identity function 162 | D = {'red','white','blue'} 163 | # Replace {...} with a one-line dictionary comprehension 164 | identity_dict = {x:x for x in D} 165 | 166 | 167 | 168 | ## 24: (Task 24) Mapping integers to their representation over a given base 169 | base = 10 170 | digits = set(range(base)) 171 | # Replace { ... } with a one-line dictionary comprehension 172 | # Your comprehension should use the variables 'base' and 'digits' so it will work correctly if these 173 | # are assigned different values (e.g. base = 2 and digits = {0,1}) 174 | representation_dict = {i:(i//base//base,i//base%base,i%base) for i in range(base*base*base) } 175 | 176 | 177 | 178 | ## 25: (Task 25) A dictionary mapping names to salaries 179 | id2salary = {0:1000.0, 1:1200.50, 2:990} 180 | names = ['Larry', 'Curly', 'Moe'] 181 | # Replace { ... } with a one-line dictionary comprehension that uses id2salary and names. 182 | listdict2dict = { names[k]:id2salary.get(k) for k in id2salary.keys()} 183 | 184 | 185 | 186 | ## 26: (Task 26) Procedure nextInts 187 | # Complete the procedure definition by replacing [ ... ] with a one-line list comprehension 188 | def nextInts(L): return [ i+1 for i in L ] 189 | 190 | 191 | 192 | ## 27: (Task 27) Procedure cubes 193 | # Complete the procedure definition by replacing [ ... ] with a one-line list comprehension 194 | def cubes(L): return [ i*i*i for i in L ] 195 | 196 | 197 | 198 | ## 28: (Task 28) Procedure dict2list 199 | # Input: a dictionary dct and a list keylist consisting of the keys of dct 200 | # Output: the list L such that L[i] is the value associated in dct with keylist[i] 201 | # Example: dict2list({'a':'A', 'b':'B', 'c':'C'},['b','c','a']) should equal ['B','C','A'] 202 | # Complete the procedure definition by replacing [ ... ] with a one-line list comprehension 203 | def dict2list(dct, keylist): return [ dct[i] for i in keylist ] 204 | 205 | 206 | 207 | ## 29: (Task 29) Procedure list2dict 208 | # Input: a list L and a list keylist of the same length 209 | # Output: the dictionary that maps keylist[i] to L[i] for i=0,1,...len(L)-1 210 | # Example: list2dict(['A','B','C'],['a','b','c']) should equal {'a':'A', 'b':'B', 'c':'C'} 211 | # Complete the procedure definition by replacing { ... } with a one-line dictionary comprehension 212 | def list2dict(L, keylist): return { keylist[i]:L[i] for i in range(len(L)) } 213 | 214 | -------------------------------------------------------------------------------- /Week0-The_Function_and_the_Field/The_Field_Problems/GF2.py: -------------------------------------------------------------------------------- 1 | # Copyright 2013 Philip N. Klein 2 | from numbers import Number 3 | 4 | class One: 5 | def __add__(self, other): return self if other == 0 else 0 6 | __sub__ = __add__ 7 | def __mul__(self, other): 8 | if isinstance(other, Number): 9 | return 0 if other == 0 else self 10 | return other 11 | def __div__(self, other): 12 | if other == 0: raise ZeroDivisionError 13 | return self 14 | __truediv__ = __div__ 15 | def __rdiv__(self,other): return other 16 | __rtruediv__ = __rdiv__ 17 | __radd__ = __add__ 18 | __rsub__ = __add__ 19 | __rmul__ = __mul__ 20 | #hack to ensure not (one < 1e-16) by ensuring not (one < x) for every x 21 | def __lt__(self,other): return False 22 | 23 | def __str__(self): return 'one' 24 | __repr__ = __str__ 25 | def __neg__(self): return self 26 | def __bool__(self): return True 27 | def __format__(self, format_spec): return format(str(self),format_spec) 28 | 29 | one = One() 30 | zero = 0 31 | -------------------------------------------------------------------------------- /Week0-The_Function_and_the_Field/The_Field_Problems/The_Field_problems.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codewatson/Coding-the-Matrix/4c855dc14d3df842336f796092c3664097a6bc03/Week0-The_Function_and_the_Field/The_Field_Problems/The_Field_problems.pdf -------------------------------------------------------------------------------- /Week0-The_Function_and_the_Field/The_Field_Problems/The_Field_problems.py: -------------------------------------------------------------------------------- 1 | # version code 75eb0ae74c69 2 | coursera = 1 3 | # Please fill out this stencil and submit using the provided submission script. 4 | 5 | 6 | 7 | 8 | 9 | ## 1: (Problem 1) Python Comprehensions: Filtering 10 | def myFilter(L, num): 11 | ''' 12 | Input: 13 | -L: a list of numbers 14 | -num: a positive integer 15 | Output: 16 | -a list of numbers not containing a multiple of num 17 | Examples: 18 | >>> myFilter([1,2,4,5,7],2) 19 | [1, 5, 7] 20 | >>> myFilter([10,15,20,25],10) 21 | [15, 25] 22 | ''' 23 | return [ x for x in L if x%num != 0] 24 | 25 | 26 | ## 2: (Problem 2) Python Comprehensions: Lists of Lists 27 | 28 | def my_lists(L): 29 | ''' 30 | >>> my_lists([1,2,4]) 31 | [[1], [1, 2], [1, 2, 3, 4]] 32 | >>> my_lists([0,3]) 33 | [[], [1, 2, 3]] 34 | ''' 35 | return [ [x+1 for x in range(i)] for i in L] 36 | 37 | 38 | ## 3: (Problem 3) Python Comprehensions: Function Composition 39 | def myFunctionComposition(f, g): 40 | ''' 41 | Input: 42 | -f: a function represented as a dictionary such that g of f exists 43 | -g: a function represented as a dictionary such that g of f exists 44 | Output: 45 | -a dictionary that represents a function g of f 46 | Examples: 47 | >>> f = {0:'a',1:'b'} 48 | >>> g = {'a':'apple','b':'banana'} 49 | >>> myFunctionComposition(f,g) == {0:'apple',1:'banana'} 50 | True 51 | 52 | >>> a = {'x':24,'y':25} 53 | >>> b = {24:'twentyfour',25:'twentyfive'} 54 | >>> myFunctionComposition(a,b) == {'x':'twentyfour','y':'twentyfive'} 55 | True 56 | ''' 57 | #return { k1:v2 for k1 in f.keys() for v2 in g.values() if f.get(k1)==g.get } 58 | k1=list(f.keys()) 59 | v1=list(f.values()) 60 | k2=list(g.keys()) 61 | v2=list(g.values()) 62 | res={} 63 | for i in range(len(f)): 64 | for j in range(len(g)): 65 | if v1[i]==k2[j]: 66 | res[k1[i]]=v2[j] 67 | return res 68 | ## 4: (Problem 4) Summing numbers in a list 69 | def mySum(L): 70 | ''' 71 | Input: 72 | a list L of numbers 73 | Output: 74 | sum of the numbers in L 75 | Be sure your procedure works for the empty list. 76 | Examples: 77 | >>> mySum([1,2,3,4]) 78 | 10 79 | >>> mySum([3,5,10]) 80 | 18 81 | ''' 82 | current = 0 83 | for x in L: 84 | current = current + x 85 | return current 86 | 87 | 88 | ## 5: (Problem 5) Multiplying numbers in a list 89 | def myProduct(L): 90 | ''' 91 | Input: 92 | -L: a list of numbers 93 | Output: 94 | -the product of the numbers in L 95 | Be sure your procedure works for the empty list. 96 | Examples: 97 | >>> myProduct([1,3,5]) 98 | 15 99 | >>> myProduct([-3,2,4]) 100 | -24 101 | ''' 102 | current = 1 103 | for x in L: 104 | current = current * x 105 | return current 106 | 107 | 108 | 109 | ## 6: (Problem 6) Minimum of a list 110 | def myMin(L): 111 | ''' 112 | Input: 113 | a list L of numbers 114 | Output: 115 | the minimum number in L 116 | Be sure your procedure works for the empty list. 117 | Hint: The value of the Python expression float('infinity') is infinity. 118 | Examples: 119 | >>> myMin([1,-100,2,3]) 120 | -100 121 | >>> myMin([0,3,5,-2,-5]) 122 | -5 123 | ''' 124 | cur = L[0] 125 | for i in range(1,len(L)): 126 | if cur > L[i]: 127 | cur = L[i] 128 | return cur 129 | 130 | 131 | 132 | ## 7: (Problem 7) Concatenation of a List 133 | def myConcat(L): 134 | ''' 135 | Input: 136 | -L:a list of strings 137 | Output: 138 | -the concatenation of all the strings in L 139 | Be sure your procedure works for the empty list. 140 | Examples: 141 | >>> myConcat(['hello','world']) 142 | 'helloworld' 143 | >>> myConcat(['what','is','up']) 144 | 'whatisup' 145 | ''' 146 | S='' 147 | for x in L: 148 | S = S + x 149 | return S 150 | 151 | 152 | ## 8: (Problem 8) Union of Sets in a List 153 | def myUnion(L): 154 | ''' 155 | Input: 156 | -L:a list of sets 157 | Output: 158 | -the union of all sets in L 159 | Be sure your procedure works for the empty list. 160 | Examples: 161 | >>> myUnion([{1,2},{2,3}]) 162 | {1, 2, 3} 163 | >>> myUnion([set(),{3,5},{3,5}]) 164 | {3, 5} 165 | ''' 166 | U=set() 167 | for x in L: 168 | U = U | x 169 | return U 170 | 171 | 172 | ## 9: (Problem 9) Complex Addition Practice 173 | # Each answer should be a Python expression whose value is a complex number. 174 | 175 | complex_addition_a = 5+3j 176 | complex_addition_b = 0+1j 177 | complex_addition_c = -1+0.001j 178 | complex_addition_d = 0.001+9j 179 | 180 | 181 | ## 10: (Problem 10) Combining Complex Operations 182 | #Write a procedure that evaluates ax+b for all elements in L 183 | 184 | def transform(a, b, L): 185 | ''' 186 | Input: 187 | -a: a number 188 | -b: a number 189 | -L: a list of numbers 190 | Output: 191 | -a list of elements where each element is ax+b where x is an element in L 192 | Examples: 193 | >>> transform(3,2,[1,2,3]) 194 | [5, 8, 11] 195 | ''' 196 | return [ a*z+b for z in L] 197 | 198 | 199 | ## 11: (Problem 11) GF(2) Arithmetic 200 | GF2_sum_1 = 1# answer with 0 or 1 201 | GF2_sum_2 = 0 202 | GF2_sum_3 = 0 203 | 204 | -------------------------------------------------------------------------------- /Week0-The_Function_and_the_Field/The_Field_Problems/image.py: -------------------------------------------------------------------------------- 1 | # Copyright 2013 Philip N. Klein 2 | """ 3 | Basic types: 4 | file - a png file on disk 5 | image - a list of list of pixels. pixels can be triples of RGB intensities, 6 | or single grayscale values. 7 | display - not a type per se, but rather causing the type to be shown on screen 8 | 9 | Functions convert between these formats, and also can write to temporary files 10 | and display them with a web browser. 11 | """ 12 | 13 | # To do: check types of arguments, check that image has no alpha channel 14 | # Note that right now, we ignore the alpha channel, but allow it. - @dbp 15 | 16 | import png 17 | import numbers 18 | import collections 19 | 20 | # Native imports 21 | import webbrowser 22 | import tempfile 23 | import os 24 | import atexit 25 | 26 | # Round color coordinate to nearest int and clamp to [0, 255] 27 | def _color_int(col): 28 | return max(min(round(col), 255), 0) 29 | 30 | # utility conversions, between boxed pixel and flat pixel formats 31 | # the png library uses flat, we use boxed. 32 | def _boxed2flat(row): 33 | return [_color_int(x) for box in row for x in box] 34 | 35 | def _flat2boxed(row): 36 | # Note we skip every 4th element, thus eliminating the alpha channel 37 | return [tuple(row[i:i+3]) for i in range(0, len(row), 4)] 38 | 39 | ## Image conversions 40 | def isgray(image): 41 | "tests whether the image is grayscale" 42 | col = image[0][0] 43 | if isinstance(col, numbers.Number): 44 | return True 45 | elif isinstance(col, collections.Iterable) and len(col) == 3: 46 | return False 47 | else: 48 | raise TypeError('Unrecognized image type') 49 | 50 | def color2gray(image): 51 | """ Converts a color image to grayscale """ 52 | # we use HDTV grayscale conversion as per https://en.wikipedia.org/wiki/Grayscale 53 | image = [[x for x in row] for row in image] 54 | return [[int(0.2126*p[0] + 0.7152*p[1] + 0.0722*p[2]) for p in row] 55 | for row in image] 56 | 57 | def gray2color(image): 58 | """ Converts a grayscale image to color """ 59 | return [[(p,p,p) for p in row] for row in image] 60 | 61 | #extracting and combining color channels 62 | def rgbsplit(image): 63 | """ Converts an RGB image to a 3-element list of grayscale images, one for each color channel""" 64 | return [[[pixel[i] for pixel in row] for row in image] for i in (0,1,2)] 65 | 66 | def rgpsplice(R,G,B): 67 | return [[(R[row][col],G[row][col],B[row][col]) for col in range(len(R[0]))] for row in range(len(R))] 68 | 69 | ## To and from files 70 | def file2image(path): 71 | """ Reads an image into a list of lists of pixel values (tuples with 72 | three values). This is a color image. """ 73 | (w, h, p, m) = png.Reader(filename = path).asRGBA() # force RGB and alpha 74 | return [_flat2boxed(r) for r in p] 75 | 76 | 77 | def image2file(image, path): 78 | """ Writes an image in list of lists format to a file. Will work with 79 | either color or grayscale. """ 80 | if isgray(image): 81 | img = gray2color(image) 82 | else: 83 | img = image 84 | with open(path, 'wb') as f: 85 | png.Writer(width=len(image[0]), height=len(image)).write(f, 86 | [_boxed2flat(r) for r in img]) 87 | 88 | ## Display functions 89 | def image2display(image, browser=None): 90 | """ Stores an image in a temporary location and displays it on screen 91 | using a web browser. """ 92 | path = _create_temp('.png') 93 | image2file(image, path) 94 | hpath = _create_temp('.html') 95 | with open(hpath, 'w') as h: 96 | h.writelines(["