├── GF2.py ├── README.md ├── The_Field_problems.pdf ├── The_Field_problems.py ├── The_Function_problems.pdf ├── The_Function_problems.py ├── The_Matrix_problems.pdf ├── The_Matrix_problems.py ├── The_Vector_Space_problems.pdf ├── The_Vector_Space_problems.py ├── The_Vector_problems.pdf ├── The_Vector_problems.py ├── UN_voting_data.txt ├── US_Senate_voting_data_109.txt ├── bitutil.py ├── coursera_submit.py ├── dictutil.py ├── ecc_lab.pdf ├── ecc_lab.py ├── image.py ├── image_mat_util.py ├── img01.png ├── inverse_index_lab.pdf ├── inverse_index_lab.py ├── inverse_index_lab_git.py ├── mat.pdf ├── mat.py ├── mat_sparsity.py ├── matutil.py ├── plotting.py ├── png.py ├── politics_lab.pdf ├── politics_lab.py ├── profile.txt ├── python_lab.pdf ├── python_lab.py ├── solver.py ├── stories_big.txt ├── stories_small.txt ├── vec.pdf ├── vec.py └── voting_record_dump109.txt /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coding-the-Matrix 2 | -------------------------------------------------------------------------------- /The_Field_problems.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LyingCortex/Coding-the-Matrix-1/118615ea85818c839dc36f4be4d2f67be307b1a8/The_Field_problems.pdf -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /The_Function_problems.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LyingCortex/Coding-the-Matrix-1/118615ea85818c839dc36f4be4d2f67be307b1a8/The_Function_problems.pdf -------------------------------------------------------------------------------- /The_Function_problems.py: -------------------------------------------------------------------------------- 1 | # version code 3e169d60c2de+ 2 | coursera = 1 3 | # Please fill out this stencil and submit using the provided submission script. 4 | 5 | 6 | 7 | 8 | 9 | ## 1: (Problem 0.8.3) Tuple Sum 10 | def tuple_sum(A, B): 11 | ''' 12 | Input: 13 | -A: a list of tuples 14 | -B: a list of tuples 15 | Output: 16 | -list of pairs (x,y) in which the first element of the 17 | ith pair is the sum of the first element of the ith pair in 18 | A and the first element of the ith pair in B 19 | Examples: 20 | >>> tuple_sum([(1,2), (10,20)],[(3,4), (30,40)]) 21 | [(4, 6), (40, 60)] 22 | ''' 23 | s=[] 24 | for i in range(len(A)): 25 | s.append((A[i][0]+B[i][0],A[i][1]+B[i][1])) 26 | return s 27 | 28 | 29 | ## 2: (Problem 0.8.4) Inverse Dictionary 30 | def inv_dict(d): 31 | ''' 32 | Input: 33 | -d: dictionary representing an invertible function f 34 | Output: 35 | -dictionary representing the inverse of f, the returned dictionary's 36 | keys are the values of d and its values are the keys of d 37 | Example: 38 | >>> inv_dict({'goodbye': 'au revoir', 'thank you': 'merci'}) == {'merci':'thank you', 'au revoir':'goodbye'} 39 | ''' 40 | dd={} 41 | k=list(d.keys()) 42 | v=list(d.values()) 43 | for i in range(len(d)): 44 | dd[v[i]]=k[i] 45 | return dd 46 | 47 | 48 | ## 3: (Problem 0.8.5) Nested Comprehension 49 | def row(p, n): 50 | ''' 51 | Input: 52 | -p: a number 53 | -n: a number 54 | Output: 55 | - n-element list such that element i is p+i 56 | Examples: 57 | >>> row(10,4) 58 | [10, 11, 12, 13] 59 | ''' 60 | s=[] 61 | for i in range(n): 62 | s.append(p+i) 63 | return s 64 | comprehension_with_row = [ row(i,20) for i in range(15) ] 65 | 66 | comprehension_without_row = [ [i+j for j in range(20)] for i in range(15) ] 67 | 68 | 69 | 70 | ## 4: (Problem 0.8.10) Probability Exercise 1 71 | Pr_f_is_even = 0.7 72 | Pr_f_is_odd = 0.3 73 | 74 | 75 | 76 | ## 5: (Problem 0.8.11) Probability Exercise 2 77 | Pr_g_is_1 = 0.4 78 | Pr_g_is_0or2 = 0.6 79 | 80 | -------------------------------------------------------------------------------- /The_Matrix_problems.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LyingCortex/Coding-the-Matrix-1/118615ea85818c839dc36f4be4d2f67be307b1a8/The_Matrix_problems.pdf -------------------------------------------------------------------------------- /The_Matrix_problems.py: -------------------------------------------------------------------------------- 1 | # version code 542eddf1f327+ 2 | coursera = 1 3 | # Please fill out this stencil and submit using the provided submission script. 4 | 5 | from mat import Mat 6 | from vec import Vec 7 | from matutil import * 8 | 9 | 10 | ## 1: (Problem 4.17.1) Computing matrix-vector products 11 | # Please represent your solution vectors as lists. 12 | vector_matrix_product_1 = [1, 0] 13 | vector_matrix_product_2 = [0, 4.44] 14 | vector_matrix_product_3 = [14, 20, 26] 15 | 16 | 17 | 18 | ## 2: (Problem 4.17.2) Matrix-vector multiplication to swap entries 19 | # Represent your solution as a list of rowlists. 20 | # For example, the 2x2 identity matrix would be [[1,0],[0,1]]. 21 | 22 | M_swap_two_vector = [[0, 1],[1,0]] 23 | 24 | 25 | 26 | ## 3: (Problem 4.17.3) [z+x, y, x] Matrix-vector multiplication 27 | three_by_three_matrix = [[1,0,1], [0,1,0], [1,0,0]] # Represent with a list of rowlists. 28 | 29 | 30 | 31 | ## 4: (Problem 4.17.4) [2x, 4y, 3z] matrix-vector multiplication 32 | multiplied_matrix = [[2, 0, 0], [0,4,0], [0,0,3]] # Represent with a list of row lists. 33 | 34 | 35 | 36 | ## 5: (Problem 4.17.5) Matrix multiplication: dimension of matrices 37 | # Please enter a boolean representing if the multiplication is valid. 38 | # If it is not valid, please enter None for the dimensions. 39 | 40 | part_1_valid = False # True or False 41 | part_1_number_rows = None # Integer or None 42 | part_1_number_cols = None # Integer or None 43 | 44 | part_2_valid = False 45 | part_2_number_rows = None 46 | part_2_number_cols = None 47 | 48 | part_3_valid = True 49 | part_3_number_rows = 1 50 | part_3_number_cols = 2 51 | 52 | part_4_valid = True 53 | part_4_number_rows = 2 54 | part_4_number_cols = 1 55 | 56 | part_5_valid = False 57 | part_5_number_rows = None 58 | part_5_number_cols = None 59 | 60 | part_6_valid = True 61 | part_6_number_rows = 1 62 | part_6_number_cols = 1 63 | 64 | part_7_valid = True 65 | part_7_number_rows = 3 66 | part_7_number_cols = 3 67 | 68 | 69 | 70 | ## 6: (Problem 4.17.6) Matrix-matrix multiplication practice with small matrices 71 | # Please represent your answer as a list of row lists. 72 | # Example: [[1,1],[2,2]] 73 | small_mat_mult_1 =[[8,13],[8,14]] 74 | small_mat_mult_2 =[[24, 11, 4],[1,3,0]] 75 | small_mat_mult_3 =[[3, 13]] 76 | small_mat_mult_4 =[[14]] 77 | small_mat_mult_5 = [[1,2,3],[2,4,6],[3,6,9]] 78 | small_mat_mult_6 = [[-2,4],[1,1],[1,-3]] 79 | 80 | 81 | 82 | ## 7: (Problem 4.17.7) Matrix-matrix multiplication practice with a permutation matrix 83 | # Please represent your solution as a list of row lists. 84 | 85 | part_1_AB = [[5,2,0,1],[2,1,-4,6],[2,3,0,-4],[-2,3,4,0]] #[[5,2,2,-2],[2,1,3,3],[0,-4,0,4],[1,6,-4,0]] 86 | part_1_BA = [[1,-4,6,2],[3,0,-4,2],[3,4,0,-2],[2,0,1,5]] 87 | 88 | part_2_AB = [[5,1,0,2],[2,6,-4,1],[2,-4,0,3],[-2,0,4,3]]#[[5,2,2,-2],[1,6,-4,0],[0,-4,0,4],[2,1,3,3]] 89 | part_2_BA = [[3,4,0,-2],[3,0,-4,2],[1,-4,6,2],[2,0,1,5]] 90 | 91 | part_3_AB = [[1,0,5,2],[6,-4,2,1],[-4,0,2,3],[0,4,-2,3]]#[[1,6,-4,0],[0,-4,0,4],[5,2,2,-2],[2,1,3,3]] 92 | part_3_BA = [[3,4,0,-2],[1,-4,6,2],[2,0,1,5],[3,0,-4,2]] 93 | 94 | 95 | 96 | ## 8: (Problem 4.17.9) Matrix-matrix multiplication practice with very sparse matrices 97 | # Please represent your answer as a list of row lists. 98 | 99 | your_answer_a_AB = [[0,0,2,0],[0,0,5,0],[0,0,4,0],[0,0,6,0]] 100 | your_answer_a_BA = [[0,0,0,0],[4,4,4,0],[0,0,0,0],[0,0,0,0]] 101 | 102 | your_answer_b_AB = [[0,2,-1,0],[0,5,3,0],[0,4,0,0],[0,6,-5,0]] 103 | your_answer_b_BA = [[0,0,0,0],[1,5,-2,3],[0,0,0,0],[4,4,4,0]] 104 | 105 | your_answer_c_AB = [[6,0,0,0],[6,0,0,0],[8,0,0,0],[5,0,0,0]] 106 | your_answer_c_BA = [[4,2,1,-1],[4,2,1,-1],[0,0,0,0],[0,0,0,0]] 107 | 108 | your_answer_d_AB = [[0,3,0,4],[0,4,0,1],[0,4,0,4],[0,-6,0,-1]] 109 | your_answer_d_BA = [[0,11,0,-2],[0,0,0,0],[0,0,0,0],[1,5,-2,3]] 110 | 111 | your_answer_e_AB = [[0,3,0,8],[0,-9,0,2],[0,0,0,8],[0,15,0,-2]] 112 | your_answer_e_BA = [[-2,12,4,-10],[0,0,0,0],[0,0,0,0],[-3,-15,6,-9]] 113 | 114 | your_answer_f_AB = [[-4,4,2,-3],[-1,10,-4,9],[-4,8,8,0],[1,12,4,-15]] 115 | your_answer_f_BA = [[-4,-2,-1,1],[2,10,-4,6],[8,8,8,0],[-3,18,6,-15]] 116 | 117 | 118 | 119 | ## 9: (Problem 4.17.11) Column-vector and row-vector matrix multiplication 120 | column_row_vector_multiplication1 = Vec({0, 1}, {0:13,1:20}) 121 | 122 | column_row_vector_multiplication2 = Vec({0, 1, 2}, {0:24,1:11,2:4}) 123 | 124 | column_row_vector_multiplication3 = Vec({0, 1, 2, 3}, {0:4,1:8,2:11,3:3}) 125 | 126 | column_row_vector_multiplication4 = Vec({0,1}, {0:30,1:16}) 127 | 128 | column_row_vector_multiplication5 = Vec({0, 1, 2}, {0:-3,1:1,2:9}) 129 | 130 | 131 | 132 | ## 10: (Problem 4.17.13) Linear-combinations matrix-vector multiply 133 | # You are also allowed to use the matutil module 134 | def lin_comb_mat_vec_mult(M, v): 135 | ''' 136 | Input: 137 | -M: a matrix 138 | -v: a vector 139 | Output: M*v 140 | The following doctests are not comprehensive; they don't test the 141 | main question, which is whether the procedure uses the appropriate 142 | linear-combination definition of matrix-vector multiplication. 143 | Examples: 144 | >>> M=Mat(({'a','b'},{0,1}), {('a',0):7, ('a',1):1, ('b',0):-5, ('b',1):2}) 145 | >>> v=Vec({0,1},{0:4, 1:2}) 146 | >>> lin_comb_mat_vec_mult(M,v) == Vec({'a', 'b'},{'a': 30, 'b': -16}) 147 | True 148 | >>> M1=Mat(({'a','b'},{0,1}), {('a',0):8, ('a',1):2, ('b',0):-2, ('b',1):1}) 149 | >>> v1=Vec({0,1},{0:4,1:3}) 150 | >>> lin_comb_mat_vec_mult(M1,v1) == Vec({'a', 'b'},{'a': 38, 'b': -5}) 151 | True 152 | ''' 153 | ''' 154 | s=Vec(M.D[0],{}) 155 | for j in v.D: 156 | tmp_vec={} 157 | for x in M.D[0]: 158 | tmp_vec[x]=M.f[x,j] 159 | s+=v[j]*Vec(M.D[0], tmp_vec) 160 | return s 161 | ''' 162 | assert(M.D[1] == v.D) 163 | #for row in M.D[0]: 164 | # for col in M.D[1]: 165 | # if (row,col) not in M.f.keys(): 166 | # M.f[(row,col)]=0 167 | #return Vec(M.D[0], { x:sum([ v[j] * M.f[(x,j)] for j in M.D[1] ]) for x in M.D[0] }) 168 | col_dict = mat2coldict(M) 169 | result_vec = Vec(M.D[0],{}) 170 | for c in v.D: 171 | result_vec = result_vec + v[c] * col_dict[c] 172 | return result_vec 173 | ## 11: (Problem 4.17.14) Linear-combinations vector-matrix multiply 174 | def lin_comb_vec_mat_mult(v, M): 175 | ''' 176 | Input: 177 | -v: a vector 178 | -M: a matrix 179 | Output: v*M 180 | The following doctests are not comprehensive; they don't test the 181 | main question, which is whether the procedure uses the appropriate 182 | linear-combination definition of vector-matrix multiplication. 183 | Examples: 184 | >>> M=Mat(({'a','b'},{0,1}), {('a',0):7, ('a',1):1, ('b',0):-5, ('b',1):2}) 185 | >>> v=Vec({'a','b'},{'a':2, 'b':-1}) 186 | >>> lin_comb_vec_mat_mult(v,M) == Vec({0, 1},{0: 19, 1: 0}) 187 | True 188 | >>> M1=Mat(({'a','b'},{0,1}), {('a',0):8, ('a',1):2, ('b',0):-2, ('b',1):1}) 189 | >>> v1=Vec({'a','b'},{'a':4,'b':3}) 190 | >>> lin_comb_vec_mat_mult(v1,M1) == Vec({0, 1},{0: 26, 1: 11}) 191 | True 192 | ''' 193 | assert(v.D == M.D[0]) 194 | #return Vec(M.D[0], { x:sum([ v[j] * M.f[(x,j)] for j in M.D[1] ]) for x in M.D[0] }) 195 | row_dict = mat2rowdict(M) 196 | result_vec = Vec(M.D[1],{}) 197 | for c in v.D: 198 | result_vec = result_vec + v[c] * row_dict[c] 199 | return result_vec 200 | 201 | 202 | 203 | ## 12: (Problem 4.17.15) dot-product matrix-vector multiply 204 | # You are also allowed to use the matutil module 205 | def dot_product_mat_vec_mult(M, v): 206 | ''' 207 | Return the matrix-vector product M*v. 208 | The following doctests are not comprehensive; they don't test the 209 | main question, which is whether the procedure uses the appropriate 210 | dot-product definition of matrix-vector multiplication. 211 | Examples: 212 | >>> M=Mat(({'a','b'},{0,1}), {('a',0):7, ('a',1):1, ('b',0):-5, ('b',1):2}) 213 | >>> v=Vec({0,1},{0:4, 1:2}) 214 | >>> dot_product_mat_vec_mult(M,v) == Vec({'a', 'b'},{'a': 30, 'b': -16}) 215 | True 216 | >>> M1=Mat(({'a','b'},{0,1}), {('a',0):8, ('a',1):2, ('b',0):-2, ('b',1):1}) 217 | >>> v1=Vec({0,1},{0:4,1:3}) 218 | >>> dot_product_mat_vec_mult(M1,v1) == Vec({'a', 'b'},{'a': 38, 'b': -5}) 219 | True 220 | ''' 221 | assert(M.D[1] == v.D) 222 | res = Vec(M.D[0], {}) 223 | row_dict = mat2rowdict(M) 224 | for r in M.D[0]: 225 | res[r]= row_dict[r] * v 226 | return res 227 | 228 | 229 | ## 13: (Problem 4.17.16) Dot-product vector-matrix multiply 230 | # You are also allowed to use the matutil module 231 | def dot_product_vec_mat_mult(v, M): 232 | ''' 233 | The following doctests are not comprehensive; they don't test the 234 | main question, which is whether the procedure uses the appropriate 235 | dot-product definition of vector-matrix multiplication. 236 | Examples: 237 | >>> M=Mat(({'a','b'},{0,1}), {('a',0):7, ('a',1):1, ('b',0):-5, ('b',1):2}) 238 | >>> v=Vec({'a','b'},{'a':2, 'b':-1}) 239 | >>> dot_product_vec_mat_mult(v,M) == Vec({0, 1},{0: 19, 1: 0}) 240 | True 241 | >>> M1=Mat(({'a','b'},{0,1}), {('a',0):8, ('a',1):2, ('b',0):-2, ('b',1):1}) 242 | >>> v1=Vec({'a','b'},{'a':4,'b':3}) 243 | >>> dot_product_vec_mat_mult(v1,M1) == Vec({0, 1},{0: 26, 1: 11}) 244 | True 245 | ''' 246 | assert(v.D == M.D[0]) 247 | res = Vec(M.D[1], {}) 248 | col_dict = mat2coldict(M) 249 | for c in M.D[1]: 250 | res[c] = col_dict[c] * v 251 | return res 252 | 253 | 254 | ## 14: (Problem 4.17.17) Matrix-vector matrix-matrix multiply 255 | # You are also allowed to use the matutil module 256 | def Mv_mat_mat_mult(A, B): 257 | assert A.D[1] == B.D[0] 258 | col_dict = mat2coldict(B) 259 | res=dict() 260 | for c in col_dict.keys(): 261 | res[c]=A*col_dict[c] 262 | return coldict2mat(res) 263 | 264 | 265 | ## 15: (Problem 4.17.18) Vector-matrix matrix-matrix multiply 266 | def vM_mat_mat_mult(A, B): 267 | assert A.D[1] == B.D[0] 268 | row_dict=mat2rowdict(A) 269 | res=dict() 270 | for r in row_dict.keys(): 271 | res[r]=row_dict[r]*B 272 | return rowdict2mat(res) 273 | 274 | 275 | ## 16: () Buttons 276 | from solver import solve 277 | from GF2 import one 278 | 279 | def D(n): return {(i,j) for i in range(n) for j in range(n)} 280 | 281 | def button_vectors(n): 282 | return {(i,j):Vec(D(n),dict([((x,j),one) for x in range(max(i-1,0), min(i+2,n))] 283 | +[((i,y),one) for y in range(max(j-1,0), min(j+2,n))])) 284 | for (i,j) in D(n)} 285 | 286 | # Remind yourself of the types of the arguments to solve(). 287 | 288 | ## PART 1 289 | 290 | b1=Vec(D(9),{(7, 8):one,(7, 7):one,(6, 2):one,(3, 7):one,(2, 5):one,(8, 5):one,(1, 2):one,(7, 2):one,(6, 3):one,(0, 4):one,(2, 2):one,(5, 0):one,(6, 4):one,(0, 0):one,(5, 4):one,(1, 4):one,(8, 7):one,(0, 8):one,(6, 5):one,(2, 7):one,(8, 3):one,(7, 0):one,(4, 6):one,(6, 8):one,(0, 6):one,(1, 8):one,(7, 4):one,(2, 4):one}) 291 | 292 | 293 | #Solution given by solver. 294 | x1 = ... 295 | 296 | #residual 297 | r1 = ... 298 | 299 | #Is x1 really a solution? Assign True if yes, False if no. 300 | is_good1 = ... 301 | 302 | ## PART 2 303 | 304 | b2=Vec(D(9), {(3,4):one, (6,7):one}) 305 | 306 | #Solution given by solver 307 | x2 = ... 308 | 309 | #residual 310 | r2 = ... 311 | 312 | #Is it really a solution? Assign True if yes, False if no. 313 | is_good2 = ... 314 | 315 | 316 | 317 | 318 | ## 17: (Problem 4.17.21) Solving 2x2 linear systems and finding matrix inverse 319 | solving_systems_x1 = -1/5.0 320 | solving_systems_x2 = 2/5.0 321 | solving_systems_y1 = 4/5 322 | solving_systems_y2 = -3/5.0 323 | solving_systems_m = Mat(({0, 1}, {0, 1}), {(0,0):-1/5.0, (1,0):2/5.0, (0,1): 4/5.0, (1,1):-3/5.0}) 324 | solving_systems_a = Mat(({0, 1}, {0, 1}), {(0,0):3, (0,1):4, (1,0):2, (1,1):1}) 325 | solving_systems_a_times_m = Mat(({0, 1}, {0, 1}), {(0,0):1, (0,1):0, (1,0):0, (1,1):1}) 326 | solving_systems_m_times_a = Mat(({0, 1}, {0, 1}), {(0,0):1, (0,1):0, (1,0):0, (1,1):1}) 327 | 328 | 329 | 330 | ## 18: (Problem 4.17.22) Matrix inverse criterion 331 | # Please write your solutions as booleans (True or False) 332 | 333 | are_inverses1 = True 334 | are_inverses2 = True 335 | are_inverses3 = False 336 | are_inverses4 = False 337 | 338 | -------------------------------------------------------------------------------- /The_Vector_Space_problems.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LyingCortex/Coding-the-Matrix-1/118615ea85818c839dc36f4be4d2f67be307b1a8/The_Vector_Space_problems.pdf -------------------------------------------------------------------------------- /The_Vector_Space_problems.py: -------------------------------------------------------------------------------- 1 | # version code 565cc389e900+ 2 | coursera = 1 3 | # Please fill out this stencil and submit using the provided submission script. 4 | 5 | from vec import Vec 6 | from itertools import * 7 | from GF2 import one 8 | 9 | 10 | ## 1: (Problem 1) Vector Comprehension and Sum 11 | def vec_select(veclist, k): 12 | ''' 13 | >>> D = {'a','b','c'} 14 | >>> v1 = Vec(D, {'a': 1}) 15 | >>> v2 = Vec(D, {'a': 0, 'b': 1}) 16 | >>> v3 = Vec(D, { 'b': 2}) 17 | >>> v4 = Vec(D, {'a': 10, 'b': 10}) 18 | >>> vec_select([v1, v2, v3, v4], 'a') == [Vec(D,{'b': 1}), Vec(D,{'b': 2})] 19 | True 20 | ''' 21 | V_L = [ v for v in veclist if v[k]==0] 22 | for v in V_L: 23 | v.f = { x:y for (x,y) in v.f.items() if x!=k } 24 | return V_L 25 | 26 | def vec_sum(veclist, D): 27 | ''' 28 | >>> D = {'a','b','c'} 29 | >>> v1 = Vec(D, {'a': 1}) 30 | >>> v2 = Vec(D, {'a': 0, 'b': 1}) 31 | >>> v3 = Vec(D, { 'b': 2}) 32 | >>> v4 = Vec(D, {'a': 10, 'b': 10}) 33 | >>> vec_sum([v1, v2, v3, v4], D) == Vec(D, {'b': 13, 'a': 11}) 34 | True 35 | ''' 36 | S=Vec(D,{}) 37 | for v in veclist: 38 | S += v 39 | return S 40 | def vec_select_sum(veclist, k, D): 41 | ''' 42 | >>> D = {'a','b','c'} 43 | >>> v1 = Vec(D, {'a': 1}) 44 | >>> v2 = Vec(D, {'a': 0, 'b': 1}) 45 | >>> v3 = Vec(D, { 'b': 2}) 46 | >>> v4 = Vec(D, {'a': 10, 'b': 10}) 47 | >>> vec_select_sum([v1, v2, v3, v4], 'a', D) == Vec(D, {'b': 3}) 48 | True 49 | ''' 50 | return vec_sum(vec_select(veclist,k), D) 51 | 52 | 53 | ## 2: (Problem 2) Vector Dictionary 54 | def scale_vecs(vecdict): 55 | ''' 56 | >>> v1 = Vec({1,2,4}, {2: 9}) 57 | >>> v2 = Vec({1,2,4}, {1: 1, 2: 2, 4: 8}) 58 | >>> result = scale_vecs({3: v1, 5: v2}) 59 | >>> len(result) 60 | 2 61 | >>> [v in [Vec({1,2,4},{2: 3.0}), Vec({1,2,4},{1: 0.2, 2: 0.4, 4: 1.6})] for v in result] 62 | [True, True] 63 | ''' 64 | #return [ Vec(v.D, { x:y/scale for (x,y) in v.f.items() }) for (scale, v) in vecdict.items() ] 65 | return [ 1/scale*v for (scale, v) in vecdict.items() ] 66 | 67 | ## 3: (Problem 3) Constructing span of given vectors over GF(2) 68 | def GF2_span(D, S): 69 | ''' 70 | >>> from GF2 import one 71 | >>> D = {'a', 'b', 'c'} 72 | >>> GF2_span(D, {Vec(D, {'a':one, 'c':one}), Vec(D, {'c':one})}) == {Vec({'a', 'b', 'c'},{}), Vec({'a', 'b', 'c'},{'a': one, 'c': one}), Vec({'a', 'b', 'c'},{'c': one}), Vec({'a', 'b', 'c'},{'a': one})} 73 | True 74 | >>> GF2_span(D, {Vec(D, {'a': one, 'b': one}), Vec(D, {'a':one}), Vec(D, {'b':one})}) == {Vec({'a', 'b', 'c'},{'a': one, 'b': one}), Vec({'a', 'b', 'c'},{'b': one}), Vec({'a', 'b', 'c'},{'a': one}), Vec({'a', 'b', 'c'},{})} 75 | True 76 | >>> S={Vec({0,1},{0:one}), Vec({0,1},{1:one})} 77 | >>> GF2_span({0,1}, S) == {Vec({0, 1},{0: one, 1: one}), Vec({0, 1},{1: one}), Vec({0, 1},{0: one}), Vec({0, 1},{})} 78 | True 79 | >>> S == {Vec({0, 1},{1: one}), Vec({0, 1},{0: one})} 80 | True 81 | ''' 82 | Span=set() 83 | for Coef in list(product([0, one], repeat=len(S))): 84 | Span.add(vec_sum([x[0]*x[1] for x in zip(Coef, S)], D)) 85 | return Span 86 | 87 | ## 4: (Problem 4) Is it a vector space 1 88 | # Answer with a boolean, please. 89 | is_a_vector_space_1 = False 90 | 91 | 92 | 93 | ## 5: (Problem 5) Is it a vector space 2 94 | # Answer with a boolean, please. 95 | is_a_vector_space_2 = True 96 | 97 | 98 | 99 | ## 6: (Problem 6) Is it a vector space 3 100 | # Answer with a boolean, please. 101 | is_a_vector_space_3 = False 102 | 103 | 104 | 105 | ## 7: (Problem 7) Is it a vector space 4 106 | # Answer with a boolean, please. 107 | is_a_vector_space_4a = True 108 | is_a_vector_space_4b = False 109 | 110 | -------------------------------------------------------------------------------- /The_Vector_problems.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LyingCortex/Coding-the-Matrix-1/118615ea85818c839dc36f4be4d2f67be307b1a8/The_Vector_problems.pdf -------------------------------------------------------------------------------- /The_Vector_problems.py: -------------------------------------------------------------------------------- 1 | # version code ef5291f09f60+ 2 | coursera = 1 3 | # Please fill out this stencil and submit using the provided submission script. 4 | 5 | # Some of the GF2 problems require use of the value GF2.one so the stencil imports it. 6 | 7 | from GF2 import one 8 | 9 | 10 | 11 | ## 1: (Problem 1) Vector Addition Practice 1 12 | #Please express each answer as a list of numbers 13 | p1_v = [-1, 3] 14 | p1_u = [0, 4] 15 | p1_v_plus_u = [-1,7] 16 | p1_v_minus_u = [-1, -1] 17 | p1_three_v_minus_two_u = [-3, 1] 18 | 19 | 20 | 21 | ## 2: (Problem 2) Vector Addition Practice 2 22 | p2_u = [-1, 1, 1] 23 | p2_v = [ 2, -1, 5] 24 | p2_v_plus_u = [1, 0, 6] 25 | p2_v_minus_u = [3, -2, 4] 26 | p2_two_v_minus_u = [5, -3, 9] 27 | p2_v_plus_two_u = [0,1,7] 28 | 29 | 30 | 31 | ## 3: (Problem 3) Vector Addition Practice 3 32 | # Write your answer using GF2's one instead of the number 1 33 | p3_vector_sum_1 = [one, 0, 0] 34 | p3_vector_sum_2 = [0, one, one] 35 | 36 | 37 | 38 | ## 4: (Problem 4) GF2 Vector Addition A 39 | # Please express your solution as a subset of the letters {'a','b','c','d','e','f'}. 40 | # For example, {'a','b','c'} is the subset consisting of: 41 | # a (1100000), b (0110000), and c (0011000). 42 | # The answer should be an empty set, written set(), if the given vector u cannot 43 | # be written as the sum of any subset of the vectors a, b, c, d, e, and f. 44 | 45 | u_0010010 = {'c','d','e'} 46 | u_0100010 = {'b','c','d','e'} 47 | 48 | 49 | ## 5: (Problem 5) GF2 Vector Addition B 50 | # Use the same format as the previous problem 51 | 52 | v_0010010 = {'c','d'} 53 | v_0100010 = set() 54 | 55 | 56 | 57 | ## 6: (Problem 6) Solving Linear Equations over GF(2) 58 | #You should be able to solve this without using a computer. 59 | x_gf2 = [1,0,0,0] 60 | 61 | 62 | 63 | ## 7: (Problem 7) Formulating Equations using Dot-Product 64 | #Please provide each answer as a list of numbers 65 | v1 = [2, 3, -4, 1] 66 | v2 = [1, -5, 2, 0] 67 | v3 = [4, 1, -1, -1] 68 | 69 | 70 | 71 | ## 8: (Problem 8) Practice with Dot-Product 72 | uv_a = 5 73 | uv_b = 6 74 | uv_c = 16 75 | uv_d = -1 76 | 77 | -------------------------------------------------------------------------------- /US_Senate_voting_data_109.txt: -------------------------------------------------------------------------------- 1 | Akaka D HI -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 0 0 1 -1 -1 1 -1 1 -1 1 1 -1 2 | Alexander R TN 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 0 1 1 3 | Allard R CO 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 4 | Allen R VA 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 5 | Baucus D MT -1 1 1 1 1 1 -1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 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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 100 | -------------------------------------------------------------------------------- /bitutil.py: -------------------------------------------------------------------------------- 1 | # Copyright 2013 Philip N. Klein 2 | """ 3 | Implements several convenience operations for use with the ECC lab. 4 | 5 | Author: Landon Judkins (ljudkins) 6 | Date: Spring 2009 7 | Updated by Nick Gaya, Spring 2013 8 | 9 | Requires: fields matutil 10 | """ 11 | 12 | from GF2 import zero, one 13 | import mat 14 | import random 15 | 16 | def str2bits(inp): 17 | """ 18 | Convert a string into a list of bits, with each character's bits in order 19 | of increasing significance. 20 | """ 21 | bs = [1<', 0) 158 | runner = ModifiedDocTestRunner() 159 | runner.run(dtst) 160 | return runner.results 161 | 162 | class ModifiedDocTestRunner(doctest.DocTestRunner): 163 | def __init__(self, *args, **kwargs): 164 | self.results = [] 165 | return super(ModifiedDocTestRunner, self).__init__(*args, checker=OutputAccepter(), **kwargs) 166 | 167 | def report_success(self, out, test, example, got): 168 | self.results.append(got) 169 | 170 | def report_unexpected_exception(self, out, test, example, exc_info): 171 | exf = traceback.format_exception_only(exc_info[0], exc_info[1])[-1] 172 | self.results.append(exf) 173 | sys.stderr.write("TEST ERROR: "+exf) #added so as not to fail silently 174 | 175 | class OutputAccepter(doctest.OutputChecker): 176 | def check_output(self, want, got, optionflags): 177 | return True 178 | 179 | def do_challenge(login, passwd, sid): 180 | login, ch, state, ch_aux = get_challenge(login, sid) 181 | if not all((login, ch, state)): 182 | print('\n!! Challenge Failed: %s\n' % login) 183 | sys.exit(1) 184 | return challenge_response(login, passwd, ch), state 185 | 186 | def get_challenge(email, sid): 187 | values = {'email_address': email, "assignment_part_sid": sid, "response_encoding": "delim"} 188 | data = urllib.parse.urlencode(values).encode('utf8') 189 | req = urllib.request.Request(challenge_url, data) 190 | with urllib.request.urlopen(req) as resp: 191 | text = resp.read().decode('utf8').strip() 192 | # text resp is email|ch|signature 193 | splits = text.split('|') 194 | if len(splits) != 9: 195 | print("Badly formatted challenge response: %s" % text) 196 | sys.exit(1) 197 | return splits[2], splits[4], splits[6], splits[8] 198 | 199 | def challenge_response(login, passwd, ch): 200 | sha1 = hashlib.sha1() 201 | sha1.update("".join([ch, passwd]).encode('utf8')) 202 | digest = sha1.hexdigest() 203 | return digest 204 | 205 | 206 | def submit(parts_string): 207 | print('= Coding the Matrix Homework and Lab Submission') 208 | 209 | print('Importing your stencil file') 210 | try: 211 | solution = __import__(asgn_name) 212 | test_vars = vars(solution).copy() 213 | except Exception as exc: 214 | print(exc) 215 | print("!! It seems that you have an error in your stencil file. Please make sure Python can import your stencil before submitting, as in...") 216 | print(""" 217 | underwood:matrix klein$ python3 218 | Python 3.4.1 219 | >>> import """+asgn_name+"\n") 220 | sys.exit(1) 221 | 222 | if not 'coursera' in test_vars: 223 | print("This is not a Coursera stencil. Make sure your stencil is obtained from http://grading.codingthematrix.com/coursera/") 224 | sys.exit(1) 225 | 226 | 227 | print('Fetching problems') 228 | source_files, problems = get_asgn_data(asgn_name) 229 | 230 | test_vars['test_format'] = test_vars['tf'] = test_format 231 | test_vars['find_lines'] = find_lines 232 | test_vars['find_line'] = find_line 233 | test_vars['use_comprehension'] = use_comprehension 234 | test_vars['double_comprehension'] = double_comprehension 235 | test_vars['line_contains_substr'] = line_contains_substr 236 | test_vars['substitute_in_assignment'] = substitute_in_assignment 237 | global login 238 | if not login: 239 | login = login_prompt() 240 | global password 241 | if not password: 242 | password = password_prompt() 243 | if not parts_string: 244 | parts_string = parts_prompt(problems) 245 | 246 | parts = parse_parts(parts_string, problems) 247 | 248 | for sid, name, part_tests in parts: 249 | print('== Submitting "%s"' % name) 250 | 251 | coursera_sid = asgn_name + '#' + sid 252 | #TODO: check challenge stuff 253 | ch_resp, state = do_challenge(login, password, coursera_sid) 254 | 255 | if dry_run: 256 | print(part_tests) 257 | else: 258 | if 'DEV' in os.environ: sid += '-dev' 259 | 260 | # to stop Coursera's strip() from doing anything, we surround in parens 261 | results = output(part_tests, test_vars) 262 | prog_out = '(%s)' % ''.join(map(str.rstrip, results)) 263 | src = source(source_files) 264 | 265 | if verbose: 266 | res_itr = iter(results) 267 | for t in part_tests.split('\n'): 268 | print(t) 269 | if t[:3] == '>>>': 270 | print(next(res_itr), end='') 271 | 272 | if show_submission: 273 | print('Submission:\n%s\n' % prog_out) 274 | 275 | feedback = submit_solution(name, coursera_sid, prog_out, src, state, ch_resp) 276 | print(feedback) 277 | 278 | 279 | def login_prompt(): 280 | return input('username: ') 281 | 282 | def password_prompt(): 283 | return input('password: ') 284 | 285 | def parts_prompt(problems): 286 | print('This assignment has the following parts:') 287 | # change to list all the possible parts? 288 | for i, (name, parts) in enumerate(problems): 289 | if parts: 290 | print(' %d) %s' % (i+1, name)) 291 | else: 292 | print(' %d) [NOT AUTOGRADED] %s' % (i+1, name)) 293 | 294 | return input('\nWhich parts do you want to submit? (Ex: 1, 4-7): ') 295 | 296 | def parse_range(s, problems): 297 | try: 298 | s = s.split('-') 299 | if len(s) == 1: 300 | index = int(s[0]) 301 | if(index == 0): 302 | return list(range(1, len(problems)+1)) 303 | else: 304 | return [int(s[0])] 305 | elif len(s) == 2: 306 | return list(range(int(s[0], 0, ), 1+int(s[1]))) 307 | except: 308 | pass 309 | return [] # Invalid value 310 | 311 | def parse_parts(string, problems): 312 | pr = lambda s: parse_range(s, problems) 313 | parts = map(pr, string.split(',')) 314 | flat_parts = sum(parts, []) 315 | return sum((problems[i-1][1] for i in flat_parts if 0>> find_error(Vec({0,1,2}, {0:one})) == Vec({0, 1, 2, 3, 4, 5, 6},{3: one}) 37 | True 38 | >>> find_error(Vec({0,1,2}, {2:one})) == Vec({0, 1, 2, 3, 4, 5, 6},{0: one}) 39 | True 40 | >>> find_error(Vec({0,1,2}, {1:one, 2:one})) == Vec({0, 1, 2, 3, 4, 5, 6},{2: one}) 41 | True 42 | >>> find_error(Vec({0,1,2}, {})) == Vec({0,1,2,3,4,5,6}, {}) 43 | True 44 | """ 45 | #return Vec({0,1,2,3,4,5,6},{}) if syndrome.f()=={} else Vec({0,1,2,3,4,5,6}, {sum[x]:one 46 | index = sum([2**(2-x) for x in syndrome.f.keys() if syndrome.f[x]==one]) 47 | if index==0: 48 | return Vec({0,1,2,3,4,5,6},{}) 49 | else: 50 | return Vec({0,1,2,3,4,5,6},{index-1:one}) 51 | ## Task 6 52 | # Use the Vec class for your answers. 53 | non_codeword = Vec({0,1,2,3,4,5,6}, {0: one, 1:0, 2:one, 3:one, 4:0, 5:one, 6:one}) 54 | error_vector = find_error(H*non_codeword) 55 | code_word = non_codeword+error_vector 56 | original = R*code_word # R * code_word 57 | #print(error_vector) 58 | #print(code_word) 59 | #print(original) 60 | 61 | ## Task 7 62 | def find_error_matrix(S): 63 | """ 64 | Input: a matrix S whose columns are error syndromes 65 | Output: a matrix whose cth column is the error corresponding to the cth column of S. 66 | Example: 67 | >>> S = listlist2mat([[0,one,one,one],[0,one,0,0],[0,0,0,one]]) 68 | >>> find_error_matrix(S) == Mat(({0, 1, 2, 3, 4, 5, 6}, {0, 1, 2, 3}), {(1, 3): 0, (3, 0): 0, (2, 1): 0, (6, 2): 0, (5, 1): one, (0, 3): 0, (4, 0): 0, (1, 2): 0, (3, 3): 0, (6, 3): 0, (5, 0): 0, (2, 2): 0, (4, 1): 0, (1, 1): 0, (3, 2): one, (0, 0): 0, (6, 0): 0, (2, 3): 0, (4, 2): 0, (1, 0): 0, (5, 3): 0, (0, 1): 0, (6, 1): 0, (3, 1): 0, (2, 0): 0, (4, 3): one, (5, 2): 0, (0, 2): 0}) 69 | True 70 | """ 71 | return coldict2mat({k: find_error(mat2coldict(S)[k]) for k in mat2coldict(S).keys()}) 72 | 73 | ## Task 8 74 | s = "I'm trying to free your mind, Neo. But I can only show you the door. You're the one that has to walk through it." 75 | P = bits2mat(str2bits(s)) 76 | 77 | ## Task 9 78 | C = G*P 79 | bits_before =len(str2bits(s)) 80 | bits_after = len(mat2bits(C)) 81 | 82 | 83 | ## Ungraded Task 84 | CTILDE = C + noise(C, 0.02) 85 | #print(s) 86 | #print(bits2str(mat2bits(CTILDE))) 87 | 88 | 89 | ## Task 10 90 | def correct(A): 91 | """ 92 | Input: a matrix A each column of which differs from a codeword in at most one bit 93 | Output: a matrix whose columns are the corresponding valid codewords. 94 | Example: 95 | >>> A = Mat(({0,1,2,3,4,5,6}, {1,2,3}), {(0,3):one, (2, 1): one, (5, 2):one, (5,3):one, (0,2): one}) 96 | >>> correct(A) == Mat(({0, 1, 2, 3, 4, 5, 6}, {1, 2, 3}), {(0, 1): 0, (1, 2): 0, (3, 2): 0, (1, 3): 0, (3, 3): 0, (5, 2): one, (6, 1): 0, (3, 1): 0, (2, 1): 0, (0, 2): one, (6, 3): one, (4, 2): 0, (6, 2): one, (2, 3): 0, (4, 3): 0, (2, 2): 0, (5, 1): 0, (0, 3): one, (4, 1): 0, (1, 1): 0, (5, 3): one}) 97 | True 98 | """ 99 | return A + find_error_matrix(H*A) 100 | 101 | #print(bits2str(mat2bits(R*correct(CTILDE)))) 102 | -------------------------------------------------------------------------------- /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(["" % path]) 97 | openinbrowser('file://%s' % hpath, browser) 98 | print("Hit Enter once the image is displayed.... ", end="") 99 | input() 100 | 101 | _browser = None 102 | 103 | def setbrowser(browser=None): 104 | """ Registers the given browser and saves it as the module default. 105 | This is used to control which browser is used to display the plot. 106 | The argument should be a value that can be passed to webbrowser.get() 107 | to obtain a browser. If no argument is given, the default is reset 108 | to the system default. 109 | 110 | webbrowser provides some predefined browser names, including: 111 | 'firefox' 112 | 'opera' 113 | 114 | If the browser string contains '%s', it is interpreted as a literal 115 | browser command line. The URL will be substituted for '%s' in the command. 116 | For example: 117 | 'google-chrome %s' 118 | 'cmd "start iexplore.exe %s"' 119 | 120 | See the webbrowser documentation for more detailed information. 121 | 122 | Note: Safari does not reliably work with the webbrowser module, 123 | so we recommend using a different browser. 124 | """ 125 | global _browser 126 | if browser is None: 127 | _browser = None # Use system default 128 | else: 129 | webbrowser.register(browser, None, webbrowser.get(browser)) 130 | _browser = browser 131 | 132 | def getbrowser(): 133 | """ Returns the module's default browser """ 134 | return _browser 135 | 136 | def openinbrowser(url, browser=None): 137 | if browser is None: 138 | browser = _browser 139 | webbrowser.get(browser).open(url) 140 | 141 | # Create a temporary file that will be removed at exit 142 | # Returns a path to the file 143 | def _create_temp(suffix='', prefix='tmp', dir=None): 144 | _f, path = tempfile.mkstemp(suffix, prefix, dir) 145 | os.close(_f) 146 | _remove_at_exit(path) 147 | return path 148 | 149 | # Register a file to be removed at exit 150 | def _remove_at_exit(path): 151 | atexit.register(os.remove, path) 152 | -------------------------------------------------------------------------------- /image_mat_util.py: -------------------------------------------------------------------------------- 1 | # Copyright 2013 Philip N. Klein 2 | """ A module for working with images in matrix format. 3 | An image is represented by two matrices, representing points and colors. 4 | The points matrix has row labels {'x', 'y', 'u'} and column labels (0,0) through (w, h), inclusive, 5 | where (w, h) are the width and height of the original image 6 | The colors matrix has row labels {'r', 'g', 'b'} and column labels (0,0) through (w-h, h-1). 7 | 8 | The column labels for these matrices represent "lattice points" on the original image. 9 | For pixel (i,j) in the original image, the (i,j) column in the colors matrix represents 10 | the pixel color and the (i,j), (i+1, j), (i+1, j+1), and (i, j+1) columns in the points 11 | matrix represent the boundary of the pixel region 12 | """ 13 | 14 | import mat 15 | import png 16 | import numbers 17 | import collections 18 | import webbrowser 19 | import tempfile 20 | import os 21 | import atexit 22 | import math 23 | 24 | # Round color coordinate to nearest int and clamp to [0, 255] 25 | def _color_int(col): 26 | return max(min(round(col), 255), 0) 27 | 28 | # utility conversions, between boxed pixel and flat pixel formats 29 | # the png library uses flat, we use boxed. 30 | def _boxed2flat(row): 31 | return [_color_int(x) for box in row for x in box] 32 | 33 | def _flat2boxed(row): 34 | # Note we skip every 4th element, thus eliminating the alpha channel 35 | return [tuple(row[i:i+3]) for i in range(0, len(row), 4)] 36 | 37 | ## Image conversions 38 | def isgray(image): 39 | "tests whether the image is grayscale" 40 | col = image[0][0] 41 | if isinstance(col, numbers.Number): 42 | return True 43 | elif isinstance(col, collections.Iterable) and len(col) == 3: 44 | return False 45 | else: 46 | raise TypeError('Unrecognized image type') 47 | 48 | def color2gray(image): 49 | """ Converts a color image to grayscale """ 50 | # we use HDTV grayscale conversion as per https://en.wikipedia.org/wiki/Grayscale 51 | return [[int(0.2126*p[0] + 0.7152*p[1] + 0.0722*p[2]) for p in row] 52 | for row in image] 53 | 54 | def gray2color(image): 55 | """ Converts a grayscale image to color """ 56 | return [[(p,p,p) for p in row] for row in image] 57 | 58 | #extracting and combining color channels 59 | def rgbsplit(image): 60 | """ Converts an RGB image to a 3-element list of grayscale images, one for each color channel""" 61 | return [[[pixel[i] for pixel in row] for row in image] for i in (0,1,2)] 62 | 63 | def rgpsplice(R,G,B): 64 | return [[(R[row][col],G[row][col],B[row][col]) for col in range(len(R[0]))] for row in range(len(R))] 65 | 66 | ## To and from files 67 | def file2image(path): 68 | """ Reads an image into a list of lists of pixel values (tuples with 69 | three values). This is a color image. """ 70 | (w, h, p, m) = png.Reader(filename = path).asRGBA() # force RGB and alpha 71 | return [_flat2boxed(r) for r in p] 72 | 73 | 74 | def image2file(image, path): 75 | """ Writes an image in list of lists format to a file. Will work with 76 | either color or grayscale. """ 77 | if isgray(image): 78 | img = gray2color(image) 79 | else: 80 | img = image 81 | with open(path, 'wb') as f: 82 | png.Writer(width=len(image[0]), height=len(image)).write(f, 83 | [_boxed2flat(r) for r in img]) 84 | 85 | ## Display functions 86 | def image2display(image, browser=None): 87 | """ Stores an image in a temporary location and displays it on screen 88 | using a web browser. """ 89 | path = _create_temp('.png') 90 | image2file(image, path) 91 | hpath = _create_temp('.html') 92 | with open(hpath, 'w') as h: 93 | h.writelines(["" % path]) 94 | openinbrowser('file://%s' % hpath, browser) 95 | print("Hit Enter once the image is displayed.... ", end="") 96 | input() 97 | 98 | _browser = None 99 | 100 | def setbrowser(browser=None): 101 | """ Registers the given browser and saves it as the module default. 102 | This is used to control which browser is used to display the plot. 103 | The argument should be a value that can be passed to webbrowser.get() 104 | to obtain a browser. If no argument is given, the default is reset 105 | to the system default. 106 | 107 | webbrowser provides some predefined browser names, including: 108 | 'firefox' 109 | 'opera' 110 | 111 | If the browser string contains '%s', it is interpreted as a literal 112 | browser command line. The URL will be substituted for '%s' in the command. 113 | For example: 114 | 'google-chrome %s' 115 | 'cmd "start iexplore.exe %s"' 116 | 117 | See the webbrowser documentation for more detailed information. 118 | 119 | Note: Safari does not reliably work with the webbrowser module, 120 | so we recommend using a different browser. 121 | """ 122 | global _browser 123 | if browser is None: 124 | _browser = None # Use system default 125 | else: 126 | webbrowser.register(browser, None, webbrowser.get(browser)) 127 | _browser = browser 128 | 129 | def getbrowser(): 130 | """ Returns the module's default browser """ 131 | return _browser 132 | 133 | def openinbrowser(url, browser=None): 134 | if browser is None: 135 | browser = _browser 136 | webbrowser.get(browser).open(url) 137 | 138 | # Create a temporary file that will be removed at exit 139 | # Returns a path to the file 140 | def _create_temp(suffix='', prefix='tmp', dir=None): 141 | _f, path = tempfile.mkstemp(suffix, prefix, dir) 142 | os.close(_f) 143 | _remove_at_exit(path) 144 | return path 145 | 146 | # Register a file to be removed at exit 147 | def _remove_at_exit(path): 148 | atexit.register(os.remove, path) 149 | 150 | def file2mat(path, row_labels = ('x', 'y', 'u')): 151 | """input: a filepath to an image in .png format 152 | output: the pair (points, matrix) of matrices representing the image.""" 153 | return image2mat(file2image(path), row_labels) 154 | 155 | def image2mat(img, row_labels = ('x', 'y', 'u')): 156 | """ input: an image in list-of-lists format 157 | output: a pair (points, colors) of matrices representing the image. 158 | Note: The input list-of-lists can consist of either integers n [0, 255] for grayscale 159 | or 3-tuple of integers representing the rgb color coordinates 160 | """ 161 | h = len(img) 162 | w = len(img[0]) 163 | rx, ry, ru = row_labels 164 | ptsD = (set(row_labels), {(x,y) for x in range(w+1) for y in range(h+1)}) 165 | ptsF = {} 166 | colorsD = ({'r', 'g', 'b'}, {(x,y) for x in range(w) for y in range(h)}) 167 | colorsF = {} 168 | for y in range(h+1): 169 | for x in range(w+1): 170 | pt = (x,y) 171 | ptsF[(rx, pt)] = x 172 | ptsF[(ry, pt)] = y 173 | ptsF[(ru, pt)] = 1 174 | if x < w and y < h: 175 | col = img[y][x] 176 | if type(col) is int: 177 | red, green, blue = col, col, col 178 | else: 179 | red, green, blue = col 180 | colorsF[('r', pt)] = red 181 | colorsF[('g', pt)] = green 182 | colorsF[('b', pt)] = blue 183 | return mat.Mat(ptsD, ptsF), mat.Mat(colorsD, colorsF) 184 | 185 | def mat2display(pts, colors, row_labels = ('x', 'y', 'u'), 186 | scale=1, xscale=None, yscale = None, xmin=0, ymin=0, xmax=None, ymax=None, 187 | crosshairs=False, browser=None): 188 | """ input: matrix pts and matrix colors representing an image 189 | result: Displays the image in a web browser 190 | 191 | Optional arguments: 192 | 193 | row_labels - A collection specifying the points matrix row labels, 194 | in order. The first element of this collection is considered the x 195 | coordinate, the second is the y coordinate, and the third is the u 196 | coordinate, which is assumed to be 1 for all points. 197 | 198 | scale - The display scale, in pixels per image coordinate unit 199 | xscale, yscale - in case you want to scale differently in x and y 200 | 201 | xmin, ymin, xmax, ymax - The region of the image to display. These can 202 | be set to None to use the minimum/maximum value of the coordinate 203 | instead of a fixed value. 204 | 205 | crosshairs - Setting this to true displays a crosshairs at (0, 0) in 206 | image coordinates 207 | 208 | browser - A browser string to be passed to webbrowser.get(). 209 | Overrides the module default, if any has been set. 210 | """ 211 | if xscale == None: xscale = scale 212 | if yscale == None: yscale = scale 213 | 214 | rx, ry, ru = row_labels 215 | if ymin is None: 216 | ymin = min(v for (k, v) in pts.f.items() if k[0] == ry) 217 | if xmin is None: 218 | xmin = min(v for (k, v) in pts.f.items() if k[0] == rx) 219 | if ymax is None: 220 | ymax = max(v for (k, v) in pts.f.items() if k[0] == ry) 221 | if xmax is None: 222 | xmax = max(v for (k, v) in pts.f.items() if k[0] == rx) 223 | 224 | # Include (0, 0) in the region 225 | if crosshairs: 226 | ymin = min(ymin, 0) 227 | xmin = min(xmin, 0) 228 | ymax = max(ymax, 0) 229 | xmax = max(xmax, 0) 230 | 231 | 232 | hpath = _create_temp('.html') 233 | with open(hpath, 'w') as h: 234 | h.writelines( 235 | ['\n', 236 | ' image \n', 237 | '\n', 238 | '\n' % ((ymax-ymin) * yscale, (xmax-xmin) * xscale), 239 | '\n' % (scale, -xmin, -ymin)]) 240 | 241 | pixels = sorted(colors.D[1]) 242 | Mx, My = pixels[-1] 243 | 244 | # go through the quads, writing each one to canvas 245 | for l in pixels: 246 | lx, ly = l 247 | r = _color_int(colors[('r', l)]) 248 | g = _color_int(colors[('g', l)]) 249 | b = _color_int(colors[('b', l)]) 250 | 251 | mx = min(lx+1, Mx)+1 252 | my = min(ly+1, My)+1 253 | 254 | # coords of corners 255 | x0 = pts[(rx, l)] 256 | y0 = pts[(ry, l)] 257 | x1 = pts[(rx, (mx, ly))] 258 | y1 = pts[(ry, (mx, ly))] 259 | x2 = pts[(rx, (mx, my))] 260 | y2 = pts[(ry, (mx, my))] 261 | x3 = pts[(rx, (lx, my))] 262 | y3 = pts[(ry, (lx, my))] 263 | 264 | h.writelines(['\n' 265 | % (x0, y0, x1, y1, x2, y2, x3, y3, r, g, b)]) 266 | 267 | # Draw crosshairs centered at (0, 0) 268 | if crosshairs: 269 | h.writelines( 270 | ['\n', 271 | '\n', 272 | '\n']) 273 | 274 | h.writelines(['\n', '\n', '\n']) 275 | 276 | openinbrowser('file://%s' % hpath, browser) 277 | print("Hit Enter once the image is displayed.... ", end="") 278 | input() 279 | -------------------------------------------------------------------------------- /img01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LyingCortex/Coding-the-Matrix-1/118615ea85818c839dc36f4be4d2f67be307b1a8/img01.png -------------------------------------------------------------------------------- /inverse_index_lab.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LyingCortex/Coding-the-Matrix-1/118615ea85818c839dc36f4be4d2f67be307b1a8/inverse_index_lab.pdf -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /mat.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LyingCortex/Coding-the-Matrix-1/118615ea85818c839dc36f4be4d2f67be307b1a8/mat.pdf -------------------------------------------------------------------------------- /mat.py: -------------------------------------------------------------------------------- 1 | # version code 542eddf1f327+ 2 | coursera = 1 3 | # Please fill out this stencil and submit using the provided submission script. 4 | 5 | # Copyright 2013 Philip N. Klein 6 | from vec import Vec 7 | 8 | #Test your Mat class over R and also over GF(2). The following tests use only R. 9 | 10 | def equal(A, B): 11 | """ 12 | Returns true iff A is equal to B. 13 | 14 | >>> Mat(({'a','b'}, {0,1}), {('a',1):0}) == Mat(({'a','b'}, {0,1}), {('b',1):0}) 15 | True 16 | >>> A = Mat(({'a','b'}, {0,1}), {('a',1):2, ('b',0):1}) 17 | >>> B = Mat(({'a','b'}, {0,1}), {('a',1):2, ('b',0):1, ('b',1):0}) 18 | >>> C = Mat(({'a','b'}, {0,1}), {('a',1):2, ('b',0):1, ('b',1):5}) 19 | >>> A == B 20 | True 21 | >>> A == C 22 | False 23 | >>> A == Mat(({'a','b'}, {0,1}), {('a',1):2, ('b',0):1}) 24 | True 25 | """ 26 | assert A.D == B.D 27 | for row in A.D[0]: 28 | for col in A.D[1]: 29 | if getitem(A,(row, col)) != getitem(B,(row, col)): 30 | return False 31 | return True 32 | 33 | 34 | def getitem(M, k): 35 | """ 36 | Returns the value of entry k in M, where k is a 2-tuple 37 | >>> M = Mat(({1,3,5}, {'a'}), {(1,'a'):4, (5,'a'): 2}) 38 | >>> M[1,'a'] 39 | 4 40 | >>> M[3,'a'] 41 | 0 42 | """ 43 | assert k[0] in M.D[0] and k[1] in M.D[1] 44 | return M.f[k] if k in M.f.keys() else 0 45 | def setitem(M, k, val): 46 | """ 47 | Set entry k of Mat M to val, where k is a 2-tuple. 48 | >>> M = Mat(({'a','b','c'}, {5}), {('a', 5):3, ('b', 5):7}) 49 | >>> M['b', 5] = 9 50 | >>> M['c', 5] = 13 51 | >>> M == Mat(({'a','b','c'}, {5}), {('a', 5):3, ('b', 5):9, ('c',5):13}) 52 | True 53 | 54 | Make sure your operations work with bizarre and unordered keys. 55 | 56 | >>> N = Mat(({((),), 7}, {True, False}), {}) 57 | >>> N[(7, False)] = 1 58 | >>> N[(((),), True)] = 2 59 | >>> N == Mat(({((),), 7}, {True, False}), {(7,False):1, (((),), True):2}) 60 | True 61 | """ 62 | assert k[0] in M.D[0] and k[1] in M.D[1] 63 | M.f[k]=val 64 | def add(A, B): 65 | """ 66 | Return the sum of Mats A and B. 67 | >>> A1 = Mat(({3, 6}, {'x','y'}), {(3,'x'):-2, (6,'y'):3}) 68 | >>> A2 = Mat(({3, 6}, {'x','y'}), {(3,'y'):4}) 69 | >>> B = Mat(({3, 6}, {'x','y'}), {(3,'x'):-2, (3,'y'):4, (6,'y'):3}) 70 | >>> A1 + A2 == B 71 | True 72 | >>> A2 + A1 == B 73 | True 74 | >>> A1 == Mat(({3, 6}, {'x','y'}), {(3,'x'):-2, (6,'y'):3}) 75 | True 76 | >>> zero = Mat(({3,6}, {'x','y'}), {}) 77 | >>> B + zero == B 78 | True 79 | >>> C1 = Mat(({1,3}, {2,4}), {(1,2):2, (3,4):3}) 80 | >>> C2 = Mat(({1,3}, {2,4}), {(1,4):1, (1,2):4}) 81 | >>> D = Mat(({1,3}, {2,4}), {(1,2):6, (1,4):1, (3,4):3}) 82 | >>> C1 + C2 == D 83 | True 84 | """ 85 | assert A.D == B.D 86 | C=A.copy() 87 | for row in A.D[0]: 88 | for col in A.D[1]: 89 | setitem(C, (row,col), getitem(A, (row,col))+getitem(B, (row,col))) 90 | return C 91 | 92 | def scalar_mul(M, x): 93 | """ 94 | Returns the result of scaling M by x. 95 | 96 | >>> M = Mat(({1,3,5}, {2,4}), {(1,2):4, (5,4):2, (3,4):3}) 97 | >>> 0*M == Mat(({1, 3, 5}, {2, 4}), {}) 98 | True 99 | >>> 1*M == M 100 | True 101 | >>> 0.25*M == Mat(({1,3,5}, {2,4}), {(1,2):1.0, (5,4):0.5, (3,4):0.75}) 102 | True 103 | """ 104 | C=M.copy() 105 | for row in M.D[0]: 106 | for col in M.D[1]: 107 | setitem(C, (row,col), x*getitem(M, (row,col))) 108 | return C 109 | 110 | def transpose(M): 111 | """ 112 | Returns the matrix that is the transpose of M. 113 | 114 | >>> M = Mat(({0,1}, {0,1}), {(0,1):3, (1,0):2, (1,1):4}) 115 | >>> M.transpose() == Mat(({0,1}, {0,1}), {(0,1):2, (1,0):3, (1,1):4}) 116 | True 117 | >>> M = Mat(({'x','y','z'}, {2,4}), {('x',4):3, ('x',2):2, ('y',4):4, ('z',4):5}) 118 | >>> Mt = Mat(({2,4}, {'x','y','z'}), {(4,'x'):3, (2,'x'):2, (4,'y'):4, (4,'z'):5}) 119 | >>> M.transpose() == Mt 120 | True 121 | """ 122 | C=Mat((M.D[1], M.D[0]),{} ) 123 | for row in M.D[0]: 124 | for col in M.D[1]: 125 | setitem(C, (col,row), getitem(M, (row,col))) 126 | return C 127 | 128 | def vector_matrix_mul(v, M): 129 | """ 130 | returns the product of vector v and matrix M 131 | 132 | >>> v1 = Vec({1, 2, 3}, {1: 1, 2: 8}) 133 | >>> M1 = Mat(({1, 2, 3}, {'a', 'b', 'c'}), {(1, 'b'): 2, (2, 'a'):-1, (3, 'a'): 1, (3, 'c'): 7}) 134 | >>> v1*M1 == Vec({'a', 'b', 'c'},{'a': -8, 'b': 2, 'c': 0}) 135 | True 136 | >>> v1 == Vec({1, 2, 3}, {1: 1, 2: 8}) 137 | True 138 | >>> M1 == Mat(({1, 2, 3}, {'a', 'b', 'c'}), {(1, 'b'): 2, (2, 'a'):-1, (3, 'a'): 1, (3, 'c'): 7}) 139 | True 140 | >>> v2 = Vec({'a','b'}, {}) 141 | >>> M2 = Mat(({'a','b'}, {0, 2, 4, 6, 7}), {}) 142 | >>> v2*M2 == Vec({0, 2, 4, 6, 7},{}) 143 | True 144 | """ 145 | assert M.D[0] == v.D 146 | v_tmp = Vec(M.D[1], {}) 147 | for col in v_tmp.D: 148 | for row in M.D[0]: 149 | v_tmp[col] = v_tmp[col] + getitem(M,(row,col)) * v[row] 150 | return v_tmp 151 | def matrix_vector_mul(M, v): 152 | """ 153 | Returns the product of matrix M and vector v. 154 | >>> N1 = Mat(({1, 3, 5, 7}, {'a', 'b'}), {(1, 'a'): -1, (1, 'b'): 2, (3, 'a'): 1, (3, 'b'):4, (7, 'a'): 3, (5, 'b'):-1}) 155 | >>> u1 = Vec({'a', 'b'}, {'a': 1, 'b': 2}) 156 | >>> N1*u1 == Vec({1, 3, 5, 7},{1: 3, 3: 9, 5: -2, 7: 3}) 157 | True 158 | >>> N1 == Mat(({1, 3, 5, 7}, {'a', 'b'}), {(1, 'a'): -1, (1, 'b'): 2, (3, 'a'): 1, (3, 'b'):4, (7, 'a'): 3, (5, 'b'):-1}) 159 | True 160 | >>> u1 == Vec({'a', 'b'}, {'a': 1, 'b': 2}) 161 | True 162 | >>> N2 = Mat(({('a', 'b'), ('c', 'd')}, {1, 2, 3, 5, 8}), {}) 163 | >>> u2 = Vec({1, 2, 3, 5, 8}, {}) 164 | >>> N2*u2 == Vec({('a', 'b'), ('c', 'd')},{}) 165 | True 166 | """ 167 | assert M.D[1] == v.D 168 | v_tmp = Vec(M.D[0], {}) 169 | for row in v_tmp.D: 170 | for col in M.D[1]: 171 | v_tmp[row] = v_tmp[row] + getitem(M,(row,col)) * v[col] 172 | return v_tmp 173 | 174 | def matrix_matrix_mul(A, B): 175 | """ 176 | Returns the result of the matrix-matrix multiplication, A*B. 177 | 178 | >>> A = Mat(({0,1,2}, {0,1,2}), {(1,1):4, (0,0):0, (1,2):1, (1,0):5, (0,1):3, (0,2):2}) 179 | >>> B = Mat(({0,1,2}, {0,1,2}), {(1,0):5, (2,1):3, (1,1):2, (2,0):0, (0,0):1, (0,1):4}) 180 | >>> A*B == Mat(({0,1,2}, {0,1,2}), {(0,0):15, (0,1):12, (1,0):25, (1,1):31}) 181 | True 182 | >>> C = Mat(({0,1,2}, {'a','b'}), {(0,'a'):4, (0,'b'):-3, (1,'a'):1, (2,'a'):1, (2,'b'):-2}) 183 | >>> D = Mat(({'a','b'}, {'x','y'}), {('a','x'):3, ('a','y'):-2, ('b','x'):4, ('b','y'):-1}) 184 | >>> C*D == Mat(({0,1,2}, {'x','y'}), {(0,'y'):-5, (1,'x'):3, (1,'y'):-2, (2,'x'):-5}) 185 | True 186 | >>> M = Mat(({0, 1}, {'a', 'c', 'b'}), {}) 187 | >>> N = Mat(({'a', 'c', 'b'}, {(1, 1), (2, 2)}), {}) 188 | >>> M*N == Mat(({0,1}, {(1,1), (2,2)}), {}) 189 | True 190 | >>> E = Mat(({'a','b'},{'A','B'}), {('a','A'):1,('a','B'):2,('b','A'):3,('b','B'):4}) 191 | >>> F = Mat(({'A','B'},{'c','d'}),{('A','d'):5}) 192 | >>> E*F == Mat(({'a', 'b'}, {'d', 'c'}), {('b', 'd'): 15, ('a', 'd'): 5}) 193 | True 194 | >>> F.transpose()*E.transpose() == Mat(({'d', 'c'}, {'a', 'b'}), {('d', 'b'): 15, ('d', 'a'): 5}) 195 | True 196 | """ 197 | assert A.D[1] == B.D[0] 198 | M=Mat((A.D[0], B.D[1]), {}) 199 | for col in B.D[1]: 200 | for row in A.D[0]: 201 | v_tmp = Vec(B.D[0], {}) 202 | for row_t in B.D[0]: 203 | v_tmp[row_t]=getitem(B, (row_t, col)) 204 | v = matrix_vector_mul(A, v_tmp) 205 | setitem(M,(row, col), v[row]) 206 | return M 207 | ################################################################################ 208 | 209 | class Mat: 210 | def __init__(self, labels, function): 211 | self.D = labels 212 | self.f = function 213 | 214 | __getitem__ = getitem 215 | __setitem__ = setitem 216 | transpose = transpose 217 | 218 | def __neg__(self): 219 | return (-1)*self 220 | 221 | def __mul__(self,other): 222 | if Mat == type(other): 223 | return matrix_matrix_mul(self,other) 224 | elif Vec == type(other): 225 | return matrix_vector_mul(self,other) 226 | else: 227 | return scalar_mul(self,other) 228 | #this will only be used if other is scalar (or not-supported). mat and vec both have __mul__ implemented 229 | 230 | def __rmul__(self, other): 231 | if Vec == type(other): 232 | return vector_matrix_mul(other, self) 233 | else: # Assume scalar 234 | return scalar_mul(self, other) 235 | 236 | __add__ = add 237 | 238 | def __radd__(self, other): 239 | "Hack to allow sum(...) to work with matrices" 240 | if other == 0: 241 | return self 242 | 243 | def __sub__(a,b): 244 | return a+(-b) 245 | 246 | __eq__ = equal 247 | 248 | def copy(self): 249 | return Mat(self.D, self.f.copy()) 250 | 251 | def __str__(M, rows=None, cols=None): 252 | "string representation for print()" 253 | if rows == None: rows = sorted(M.D[0], key=repr) 254 | if cols == None: cols = sorted(M.D[1], key=repr) 255 | separator = ' | ' 256 | numdec = 3 257 | pre = 1+max([len(str(r)) for r in rows]) 258 | colw = {col:(1+max([len(str(col))] + [len('{0:.{1}G}'.format(M[row,col],numdec)) if isinstance(M[row,col], int) or isinstance(M[row,col], float) else len(str(M[row,col])) for row in rows])) for col in cols} 259 | s1 = ' '*(1+ pre + len(separator)) 260 | s2 = ''.join(['{0:>{1}}'.format(str(c),colw[c]) for c in cols]) 261 | s3 = ' '*(pre+len(separator)) + '-'*(sum(list(colw.values())) + 1) 262 | s4 = ''.join(['{0:>{1}} {2}'.format(str(r), pre,separator)+''.join(['{0:>{1}.{2}G}'.format(M[r,c],colw[c],numdec) if isinstance(M[r,c], int) or isinstance(M[r,c], float) else '{0:>{1}}'.format(M[r,c], colw[c]) for c in cols])+'\n' for r in rows]) 263 | return '\n' + s1 + s2 + '\n' + s3 + '\n' + s4 264 | 265 | def pp(self, rows, cols): 266 | print(self.__str__(rows, cols)) 267 | 268 | def __repr__(self): 269 | "evaluatable representation" 270 | return "Mat(" + str(self.D) +", " + str(self.f) + ")" 271 | 272 | def __iter__(self): 273 | raise TypeError('%r object is not iterable' % self.__class__.__name__) 274 | -------------------------------------------------------------------------------- /mat_sparsity.py: -------------------------------------------------------------------------------- 1 | ''' 2 | >>> from mat import Mat 3 | >>> from vec import Vec 4 | >>> (Mat((set(range(10000)),set(range(100000))),{(0,0):1})*Vec(set(range(100000)),{0:2}))[0] 5 | 2 6 | >>> (Vec(set(range(100000)),{0:2})*Mat((set(range(10000)),set(range(100000))),{(0,0):1}).transpose())[0] 7 | 2 8 | >>> (Mat((set(range(10000)),set(range(100000))),{(0,0):1})*Mat((set(range(100000)), set(range(9999))), {(0,0):2}))[0,0] 9 | 2 10 | ''' 11 | -------------------------------------------------------------------------------- /matutil.py: -------------------------------------------------------------------------------- 1 | # Copyright 2013 Philip N. Klein 2 | from vec import Vec 3 | from mat import Mat 4 | 5 | def efficient_rowdict2mat(rowdict): 6 | col_labels = value(rowdict).D 7 | M = Mat((set(keys(rowdict)), col_labels), {}) 8 | for r in rowdict: 9 | for c in rowdict[r].f: 10 | M[r,c] = rowdict[r][c] 11 | return M 12 | 13 | def identity(D, one): 14 | """Given a set D and the field's one, returns the DxD identity matrix 15 | e.g.: 16 | 17 | >>> identity({0,1,2}, 1) 18 | Mat(({0, 1, 2}, {0, 1, 2}), {(0, 0): 1, (1, 1): 1, (2, 2): 1}) 19 | """ 20 | return Mat((D,D), {(d,d):one for d in D}) 21 | 22 | def keys(d): 23 | """Given a dict, returns something that generates the keys; given a list, 24 | returns something that generates the indices. Intended for coldict2mat and rowdict2mat. 25 | """ 26 | return d.keys() if isinstance(d, dict) else range(len(d)) 27 | 28 | def value(d): 29 | """Given either a dict or a list, returns one of the values. 30 | Intended for coldict2mat and rowdict2mat. 31 | """ 32 | return next(iter(d.values())) if isinstance(d, dict) else d[0] 33 | 34 | def mat2rowdict(A): 35 | """Given a matrix, return a dictionary mapping row labels of A to rows of A 36 | e.g.: 37 | 38 | >>> M = Mat(({0, 1, 2}, {0, 1}), {(0, 1): 1, (2, 0): 8, (1, 0): 4, (0, 0): 3, (2, 1): -2}) 39 | >>> mat2rowdict(M) 40 | {0: Vec({0, 1},{0: 3, 1: 1}), 1: Vec({0, 1},{0: 4, 1: 0}), 2: Vec({0, 1},{0: 8, 1: -2})} 41 | >>> mat2rowdict(Mat(({0,1},{0,1}),{})) 42 | {0: Vec({0, 1},{0: 0, 1: 0}), 1: Vec({0, 1},{0: 0, 1: 0})} 43 | """ 44 | return {row:Vec(A.D[1], {col:A[row,col] for col in A.D[1]}) for row in A.D[0]} 45 | 46 | def mat2coldict(A): 47 | """Given a matrix, return a dictionary mapping column labels of A to columns of A 48 | e.g.: 49 | >>> M = Mat(({0, 1, 2}, {0, 1}), {(0, 1): 1, (2, 0): 8, (1, 0): 4, (0, 0): 3, (2, 1): -2}) 50 | >>> mat2coldict(M) 51 | {0: Vec({0, 1, 2},{0: 3, 1: 4, 2: 8}), 1: Vec({0, 1, 2},{0: 1, 1: 0, 2: -2})} 52 | >>> mat2coldict(Mat(({0,1},{0,1}),{})) 53 | {0: Vec({0, 1},{0: 0, 1: 0}), 1: Vec({0, 1},{0: 0, 1: 0})} 54 | """ 55 | return {col:Vec(A.D[0], {row:A[row,col] for row in A.D[0]}) for col in A.D[1]} 56 | 57 | def coldict2mat(coldict): 58 | """ 59 | Given a dictionary or list whose values are Vecs, returns the Mat having these 60 | Vecs as its columns. This is the inverse of mat2coldict. 61 | Assumes all the Vecs have the same label-set. 62 | Assumes coldict is nonempty. 63 | If coldict is a dictionary then its keys will be the column-labels of the Mat. 64 | If coldict is a list then {0...len(coldict)-1} will be the column-labels of the Mat. 65 | e.g.: 66 | 67 | >>> A = {0:Vec({0,1},{0:1,1:2}),1:Vec({0,1},{0:3,1:4})} 68 | >>> B = [Vec({0,1},{0:1,1:2}),Vec({0,1},{0:3,1:4})] 69 | >>> mat2coldict(coldict2mat(A)) == A 70 | True 71 | >>> coldict2mat(A) 72 | Mat(({0, 1}, {0, 1}), {(0, 1): 3, (1, 0): 2, (0, 0): 1, (1, 1): 4}) 73 | >>> coldict2mat(A) == coldict2mat(B) 74 | True 75 | """ 76 | row_labels = value(coldict).D 77 | return Mat((row_labels, set(keys(coldict))), {(r,c):coldict[c][r] for c in keys(coldict) for r in row_labels}) 78 | 79 | def rowdict2mat(rowdict): 80 | """ 81 | Given a dictionary or list whose values are Vecs, returns the Mat having these 82 | Vecs as its rows. This is the inverse of mat2rowdict. 83 | Assumes all the Vecs have the same label-set. 84 | Assumes row_dict is nonempty. 85 | If rowdict is a dictionary then its keys will be the row-labels of the Mat. 86 | If rowdict is a list then {0...len(rowdict)-1} will be the row-labels of the Mat. 87 | e.g.: 88 | 89 | >>> A = {0:Vec({0,1},{0:1,1:2}),1:Vec({0,1},{0:3,1:4})} 90 | >>> B = [Vec({0,1},{0:1,1:2}),Vec({0,1},{0:3,1:4})] 91 | >>> mat2rowdict(rowdict2mat(A)) == A 92 | True 93 | >>> rowdict2mat(A) 94 | Mat(({0, 1}, {0, 1}), {(0, 1): 2, (1, 0): 3, (0, 0): 1, (1, 1): 4}) 95 | >>> rowdict2mat(A) == rowdict2mat(B) 96 | True 97 | """ 98 | col_labels = value(rowdict).D 99 | return Mat((set(keys(rowdict)), col_labels), {(r,c):rowdict[r][c] for r in keys(rowdict) for c in col_labels}) 100 | 101 | def listlist2mat(L): 102 | """Given a list of lists of field elements, return a matrix whose ith row consists 103 | of the elements of the ith list. The row-labels are {0...len(L)}, and the 104 | column-labels are {0...len(L[0])} 105 | >>> A=listlist2mat([[10,20,30,40],[50,60,70,80]]) 106 | >>> print(A) 107 | 108 | 0 1 2 3 109 | ------------- 110 | 0 | 10 20 30 40 111 | 1 | 50 60 70 80 112 | 113 | """ 114 | m,n = len(L), len(L[0]) 115 | return Mat((set(range(m)),set(range(n))), {(r,c):L[r][c] for r in range(m) for c in range(n)}) 116 | 117 | def submatrix(M, rows, cols): 118 | return Mat((M.D[0]&rows, M.D[1]&cols), {(r,c):val for (r,c),val in M.f.items() if r in rows and c in cols}) 119 | -------------------------------------------------------------------------------- /plotting.py: -------------------------------------------------------------------------------- 1 | # Copyright 2013 Philip N. Klein 2 | """ 3 | This file contains a simple plotting interface, which uses a browser with SVG to 4 | present a plot of points represented as either complex numbers or 2-vectors. 5 | 6 | """ 7 | 8 | import webbrowser 9 | from numbers import Number 10 | 11 | import tempfile 12 | import os 13 | import atexit 14 | 15 | _browser = None 16 | 17 | def plot(L, scale=4, dot_size = 3, browser=None): 18 | """ plot takes a list of points, optionally a scale (relative to a 200x200 frame), 19 | optionally a dot size (diameter) in pixels, and optionally a browser name. 20 | It produces an html file with SVG representing the given plot, 21 | and opens the file in a web browser. It returns nothing. 22 | """ 23 | scalar = 200./scale 24 | origin = (210, 210) 25 | hpath = create_temp('.html') 26 | with open(hpath, 'w') as h: 27 | h.writelines( 28 | ['\n' 29 | ,'\n' 30 | ,'plot\n' 31 | ,'\n' 32 | ,'\n' 33 | ,'\n' 34 | ,'\n' 36 | ,'\n']) 38 | for pt in L: 39 | if isinstance(pt, Number): 40 | x,y = pt.real, pt.imag 41 | else: 42 | if isinstance(pt, tuple) or isinstance(pt, list): 43 | x,y = pt 44 | else: 45 | raise ValueError 46 | h.writelines(['\n' 47 | % (origin[0]+scalar*x,origin[1]-scalar*y,dot_size)]) 48 | h.writelines(['\n\n']) 49 | if browser is None: 50 | browser = _browser 51 | webbrowser.get(browser).open('file://%s' % hpath) 52 | 53 | def setbrowser(browser=None): 54 | """ Registers the given browser and saves it as the module default. 55 | This is used to control which browser is used to display the plot. 56 | The argument should be a value that can be passed to webbrowser.get() 57 | to obtain a browser. If no argument is given, the default is reset 58 | to the system default. 59 | 60 | webbrowser provides some predefined browser names, including: 61 | 'firefox' 62 | 'opera' 63 | 64 | If the browser string contains '%s', it is interpreted as a literal 65 | browser command line. The URL will be substituted for '%s' in the command. 66 | For example: 67 | 'google-chrome %s' 68 | 'cmd "start iexplore.exe %s"' 69 | 70 | See the webbrowser documentation for more detailed information. 71 | 72 | Note: Safari does not reliably work with the webbrowser module, 73 | so we recommend using a different browser. 74 | """ 75 | global _browser 76 | if browser is None: 77 | _browser = None # Use system default 78 | else: 79 | webbrowser.register(browser, None, webbrowser.get(browser)) 80 | _browser = browser 81 | 82 | def getbrowser(): 83 | """ Returns the module's default browser """ 84 | return _browser 85 | 86 | # Create a temporary file that will be removed at exit 87 | # Returns a path to the file 88 | def create_temp(suffix='', prefix='tmp', dir=None): 89 | _f, path = tempfile.mkstemp(suffix, prefix, dir) 90 | os.close(_f) 91 | remove_at_exit(path) 92 | return path 93 | 94 | # Register a file to be removed at exit 95 | def remove_at_exit(path): 96 | atexit.register(os.remove, path) 97 | -------------------------------------------------------------------------------- /politics_lab.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LyingCortex/Coding-the-Matrix-1/118615ea85818c839dc36f4be4d2f67be307b1a8/politics_lab.pdf -------------------------------------------------------------------------------- /politics_lab.py: -------------------------------------------------------------------------------- 1 | # version code 77ed2409f40d+ 2 | coursera = 1 3 | # Please fill out this stencil and submit using the provided submission script. 4 | 5 | # Be sure that the file voting_record_dump109.txt is in the matrix/ directory. 6 | 7 | 8 | 9 | 10 | 11 | ## 1: (Task 2.12.1) Create Voting Dict 12 | def create_voting_dict(strlist): 13 | """ 14 | Input: a list of strings. Each string represents the voting record of a senator. 15 | The string consists of 16 | - the senator's last name, 17 | - a letter indicating the senator's party, 18 | - a couple of letters indicating the senator's home state, and 19 | - a sequence of numbers (0's, 1's, and negative 1's) indicating the senator's 20 | votes on bills 21 | all separated by spaces. 22 | Output: A dictionary that maps the last name of a senator 23 | to a list of numbers representing the senator's voting record. 24 | Example: 25 | >>> vd = create_voting_dict(['Kennedy D MA -1 -1 1 1', 'Snowe R ME 1 1 1 1']) 26 | >>> vd == {'Snowe': [1, 1, 1, 1], 'Kennedy': [-1, -1, 1, 1]} 27 | True 28 | 29 | You can use the .split() method to split each string in the 30 | strlist into a list; the first element of the list will be the senator's 31 | name, the second will be his/her party affiliation (R or D), the 32 | third will be his/her home state, and the remaining elements of 33 | the list will be that senator's voting record on a collection of bills. 34 | 35 | You can use the built-in procedure int() to convert a string 36 | representation of an integer (e.g. '1') to the actual integer 37 | (e.g. 1). 38 | 39 | The lists for each senator should preserve the order listed in voting data. 40 | In case you're feeling clever, this can be done in one line. 41 | """ 42 | d={} 43 | for tmp in strlist: 44 | tmp_l = tmp.split() 45 | d[tmp_l[0]]=[ int(tmp_l[i]) for i in range(3, len(tmp_l)) ] 46 | return d 47 | 48 | 49 | ## 2: (Task 2.12.2) Policy Compare 50 | def policy_compare(sen_a, sen_b, voting_dict): 51 | """ 52 | Input: last names of sen_a and sen_b, and a voting dictionary mapping senator 53 | names to lists representing their voting records. 54 | Output: the dot-product (as a number) representing the degree of similarity 55 | between two senators' voting policies 56 | Example: 57 | >>> voting_dict = {'Fox-Epstein':[-1,-1,-1,1],'Ravella':[1,1,1,1]} 58 | >>> policy_compare('Fox-Epstein','Ravella', voting_dict) 59 | -2 60 | 61 | The code should correct compute dot-product even if the numbers are not all in {0,1,-1}. 62 | >>> policy_compare('A', 'B', {'A':[100,10,1], 'B':[2,5,3]}) 63 | 253 64 | 65 | You should definitely try to write this in one line. 66 | """ 67 | return sum([ x[0]*x[1] for x in zip(voting_dict[sen_a], voting_dict[sen_b]) ]) 68 | 69 | 70 | 71 | ## 3: (Task 2.12.3) Most Similar 72 | def most_similar(sen, voting_dict): 73 | """ 74 | Input: the last name of a senator, and a dictionary mapping senator names 75 | to lists representing their voting records. 76 | Output: the last name of the senator whose political mindset is most 77 | like the input senator (excluding, of course, the input senator 78 | him/herself). Resolve ties arbitrarily. 79 | Example: 80 | >>> vd = {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]} 81 | >>> most_similar('Klein', vd) 82 | 'Fox-Epstein' 83 | >>> vd == {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]} 84 | True 85 | >>> vd = {'a': [1,1,1], 'b': [1,-1,0], 'c': [-1,0,0], 'd': [-1,0,0], 'e': [1, 0, 0]} 86 | >>> most_similar('c', vd) 87 | 'd' 88 | 89 | Note that you can (and are encouraged to) re-use your policy_compare procedure. 90 | """ 91 | M=-float('infinity') 92 | K="" 93 | for k in list(voting_dict.keys()): 94 | if k != sen and M <= policy_compare(sen, k, voting_dict): 95 | M=policy_compare(sen, k, voting_dict) 96 | K=k 97 | return K 98 | 99 | 100 | 101 | ## 4: (Task 2.12.4) Least Similar 102 | def least_similar(sen, voting_dict): 103 | """ 104 | Input: the last name of a senator, and a dictionary mapping senator names 105 | to lists representing their voting records. 106 | Output: the last name of the senator whose political mindset is least like the input 107 | senator. 108 | Example: 109 | >>> vd = {'a': [1,1,1], 'b': [1,-1,0], 'c': [-1,0,0]} 110 | >>> least_similar('a', vd) 111 | 'c' 112 | >>> vd == {'a': [1,1,1], 'b': [1,-1,0], 'c': [-1,0,0]} 113 | True 114 | >>> vd = {'a': [-1,0,0], 'b': [1,0,0], 'c': [-1,0,0]} 115 | >>> least_similar('c', vd) 116 | 'b' 117 | """ 118 | M=float('infinity') 119 | K="" 120 | for k in list(voting_dict.keys()): 121 | if k != sen and M >= policy_compare(sen, k, voting_dict): 122 | M=policy_compare(sen, k, voting_dict) 123 | K=k 124 | return K 125 | 126 | 127 | 128 | ## 5: (Task 2.12.5) Chafee, Santorum 129 | most_like_chafee = 'Jeffords' 130 | least_like_santorum = 'Feingold' 131 | 132 | 133 | 134 | ## 6: (Task 2.12.7) Most Average Democrat 135 | def find_average_similarity(sen, sen_set, voting_dict): 136 | """ 137 | Input: the name of a senator, a set of senator names, and a voting dictionary. 138 | Output: the average dot-product between sen and those in sen_set. 139 | Example: 140 | >>> vd = {'Klein':[1,1,1], 'Fox-Epstein':[1,-1,0], 'Ravella':[-1,0,0], 'Oyakawa':[-1,-1,-1], 'Loery':[0,1,1]} 141 | >>> sens = {'Fox-Epstein','Ravella','Oyakawa','Loery'} 142 | >>> find_average_similarity('Klein', sens, vd) 143 | -0.5 144 | >>> sens == {'Fox-Epstein','Ravella', 'Oyakawa', 'Loery'} 145 | True 146 | >>> vd == {'Klein':[1,1,1], 'Fox-Epstein':[1,-1,0], 'Ravella':[-1,0,0], 'Oyakawa':[-1,-1,-1], 'Loery':[0,1,1]} 147 | True 148 | """ 149 | return sum([ policy_compare(sen, k, voting_dict) for k in sen_set ])/len(sen_set) 150 | 151 | most_average_Democrat = "Biden" # give the last name (or code that computes the last name) 152 | # f= open('voting_record_dump109.txt') 153 | # mylist=list(f) 154 | # vd = create_voting_dict(mylist) 155 | # print(most_similar("Chafee",vd)) 156 | # print(least_similar("Santorum",vd)) 157 | # sen_set={ L.split()[0] for L in mylist if L.split()[1] == 'D'} 158 | # print(sen_set) 159 | # most_average_Democrat = "" 160 | # Max=-float('infinity') 161 | # for L in mylist: #find_average_similarity(sen, sen_set, vd) 162 | # if find_average_similarity(L.split()[0], sen_set, vd)>=Max: 163 | # Max=find_average_similarity(L.split()[0], sen_set, vd) 164 | # most_average_Democrat = L.split()[0] 165 | # print(most_average_Democrat) 166 | 167 | 168 | ## 7: (Task 2.12.8) Average Record 169 | def find_average_record(sen_set, voting_dict): 170 | """ 171 | Input: a set of last names, a voting dictionary 172 | Output: a vector containing the average components of the voting records 173 | of the senators in the input set 174 | Example: 175 | >>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]} 176 | >>> senators = {'Fox-Epstein','Ravella'} 177 | >>> find_average_record(senators, voting_dict) 178 | [-0.5, -0.5, 0.0] 179 | >>> voting_dict == {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]} 180 | True 181 | >>> senators 182 | {'Fox-Epstein','Ravella'} 183 | >>> d = {'c': [-1,-1,0], 'b': [0,1,1], 'a': [0,1,1], 'e': [-1,-1,1], 'd': [-1,1,1]} 184 | >>> find_average_record({'a','c','e'}, d) 185 | [-0.6666666666666666, -0.3333333333333333, 0.6666666666666666] 186 | >>> find_average_record({'a','c','e','b'}, d) 187 | [-0.5, 0.0, 0.75] 188 | >>> find_average_record({'a'}, d) 189 | [0.0, 1.0, 1.0] 190 | """ 191 | #return sum([ policy_compare(k, k, voting_dict) for k in sen_set ])/len(sen_set) 192 | sen_L= [ 0 for x in range(len(list(voting_dict.values())[0]))] 193 | for sen in sen_set: 194 | sen_L= [ sum(x) for x in zip(voting_dict[sen],sen_L) ] 195 | return [ x/len(sen_set) for x in sen_L] 196 | average_Democrat_record = [-0.16279069767441862, -0.23255813953488372, 1.0, 0.8372093023255814, 0.9767441860465116, -0.13953488372093023, -0.9534883720930233, 0.813953488372093, 0.9767441860465116, 0.9767441860465116, 0.9069767441860465, 0.7674418604651163, 0.6744186046511628, 0.9767441860465116, -0.5116279069767442, 0.9302325581395349, 0.9534883720930233, 0.9767441860465116, -0.3953488372093023, 0.9767441860465116, 1.0, 1.0, 1.0, 0.9534883720930233, -0.4883720930232558, 1.0, -0.32558139534883723, -0.06976744186046512, 0.9767441860465116, 0.8604651162790697, 0.9767441860465116, 0.9767441860465116, 1.0, 1.0, 0.9767441860465116, -0.3488372093023256, 0.9767441860465116, -0.4883720930232558, 0.23255813953488372, 0.8837209302325582, 0.4418604651162791, 0.9069767441860465, -0.9069767441860465, 1.0, 0.9069767441860465, -0.3023255813953488]# give the vector as a list 197 | # print(find_average_record(sen_set, vd)) 198 | 199 | 200 | ## 8: (Task 2.12.9) Bitter Rivals 201 | def bitter_rivals(voting_dict): 202 | """ 203 | Input: a dictionary mapping senator names to lists representing 204 | their voting records 205 | Output: a tuple containing the two senators who most strongly 206 | disagree with one another. 207 | Example: 208 | >>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]} 209 | >>> br = bitter_rivals(voting_dict) 210 | >>> br == ('Fox-Epstein', 'Ravella') or br == ('Ravella', 'Fox-Epstein') 211 | True 212 | """ 213 | x="" 214 | y="" 215 | M=float("infinity") 216 | for sen_a in voting_dict.keys(): 217 | for sen_b in voting_dict.keys(): 218 | if sen_a != sen_b and M >= policy_compare(sen_a, sen_b, voting_dict): 219 | M = policy_compare(sen_a, sen_b, voting_dict) 220 | x = sen_a 221 | y = sen_b 222 | return (x,y) 223 | 224 | -------------------------------------------------------------------------------- /profile.txt: -------------------------------------------------------------------------------- 1 | USERNAME liuqunxyz@gmail.com 2 | PASSWORD J5k9bcq2KM -------------------------------------------------------------------------------- /python_lab.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LyingCortex/Coding-the-Matrix-1/118615ea85818c839dc36f4be4d2f67be307b1a8/python_lab.pdf -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /vec.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LyingCortex/Coding-the-Matrix-1/118615ea85818c839dc36f4be4d2f67be307b1a8/vec.pdf -------------------------------------------------------------------------------- /vec.py: -------------------------------------------------------------------------------- 1 | # version code 24ea27739109+ 2 | coursera = 1 3 | # Please fill out this stencil and submit using the provided submission script. 4 | 5 | # Copyright 2013 Philip N. Klein 6 | 7 | def getitem(v,k): 8 | """ 9 | Return the value of entry k in v. 10 | Be sure getitem(v,k) returns 0 if k is not represented in v.f. 11 | 12 | >>> v = Vec({'a','b','c', 'd'},{'a':2,'c':1,'d':3}) 13 | >>> v['d'] 14 | 3 15 | >>> v['b'] 16 | 0 17 | """ 18 | return v.f[k] if k in v.f.keys() else 0 19 | def setitem(v,k,val): 20 | """ 21 | Set the element of v with label d to be val. 22 | setitem(v,d,val) should set the value for key d even if d 23 | is not previously represented in v.f. 24 | 25 | >>> v = Vec({'a', 'b', 'c'}, {'b':0}) 26 | >>> v['b'] = 5 27 | >>> v['b'] 28 | 5 29 | >>> v['a'] = 1 30 | >>> v['a'] 31 | 1 32 | >>> v['a'] = 0 33 | >>> v['a'] 34 | 0 35 | """ 36 | v.f[k]=val 37 | 38 | def equal(u,v): 39 | """ 40 | Return true iff u is equal to v. 41 | Because of sparse representation, it is not enough to compare dictionaries 42 | 43 | >>> Vec({'a', 'b', 'c'}, {'a':0}) == Vec({'a', 'b', 'c'}, {'b':0}) 44 | True 45 | 46 | Be sure that equal(u, v) check equalities for all keys from u.f and v.f even if 47 | some keys in u.f do not exist in v.f (or vice versa) 48 | 49 | >>> Vec({'x','y','z'},{'y':1,'x':2}) == Vec({'x','y','z'},{'y':1,'z':0}) 50 | False 51 | >>> Vec({'a','b','c'}, {'a':0,'c':1}) == Vec({'a','b','c'}, {'a':0,'c':1,'b':4}) 52 | False 53 | >>> Vec({'a','b','c'}, {'a':0,'c':1,'b':4}) == Vec({'a','b','c'}, {'a':0,'c':1}) 54 | False 55 | 56 | The keys matter: 57 | >>> Vec({'a','b'},{'a':1}) == Vec({'a','b'},{'b':1}) 58 | False 59 | 60 | The values matter: 61 | >>> Vec({'a','b'},{'a':1}) == Vec({'a','b'},{'a':2}) 62 | False 63 | 64 | """ 65 | assert u.D == v.D 66 | for k in u.D: 67 | if getitem(u,k)!=getitem(v,k): 68 | return False 69 | return True 70 | 71 | def add(u,v): 72 | """ 73 | Returns the sum of the two vectors. 74 | Make sure to add together values for all keys from u.f and v.f even if some keys in u.f do not 75 | exist in v.f (or vice versa) 76 | 77 | >>> a = Vec({'a','e','i','o','u'}, {'a':0,'e':1,'i':2}) 78 | >>> b = Vec({'a','e','i','o','u'}, {'o':4,'u':7}) 79 | >>> c = Vec({'a','e','i','o','u'}, {'a':0,'e':1,'i':2,'o':4,'u':7}) 80 | >>> a + b == c 81 | True 82 | >>> a == Vec({'a','e','i','o','u'}, {'a':0,'e':1,'i':2}) 83 | True 84 | >>> b == Vec({'a','e','i','o','u'}, {'o':4,'u':7}) 85 | True 86 | >>> d = Vec({'x','y','z'}, {'x':2,'y':1}) 87 | >>> e = Vec({'x','y','z'}, {'z':4,'y':-1}) 88 | >>> f = Vec({'x','y','z'}, {'x':2,'y':0,'z':4}) 89 | >>> d + e == f 90 | True 91 | >>> b + Vec({'a','e','i','o','u'}, {}) == b 92 | True 93 | """ 94 | assert u.D == v.D 95 | s=u.copy() 96 | for k in u.D: 97 | setitem(s,k,getitem(u,k)+getitem(v,k)) 98 | return s 99 | def dot(u,v): 100 | """ 101 | Returns the dot product of the two vectors. 102 | 103 | >>> u1 = Vec({'a','b'}, {'a':1, 'b':2}) 104 | >>> u2 = Vec({'a','b'}, {'b':2, 'a':1}) 105 | >>> u1*u2 106 | 5 107 | >>> u1 == Vec({'a','b'}, {'a':1, 'b':2}) 108 | True 109 | >>> u2 == Vec({'a','b'}, {'b':2, 'a':1}) 110 | True 111 | >>> v1 = Vec({'p','q','r','s'}, {'p':2,'s':3,'q':-1,'r':0}) 112 | >>> v2 = Vec({'p','q','r','s'}, {'p':-2,'r':5}) 113 | >>> v1*v2 114 | -4 115 | >>> w1 = Vec({'a','b','c'}, {'a':2,'b':3,'c':4}) 116 | >>> w2 = Vec({'a','b','c'}, {'a':12,'b':8,'c':6}) 117 | >>> w1*w2 118 | 72 119 | 120 | The pairwise products should not be collected in a set before summing 121 | because a set eliminates duplicates 122 | >>> v1 = Vec({1, 2}, {1 : 3, 2 : 6}) 123 | >>> v2 = Vec({1, 2}, {1 : 2, 2 : 1}) 124 | >>> v1 * v2 125 | 12 126 | """ 127 | assert u.D == v.D 128 | s=0 129 | for k in u.D: 130 | s+= getitem(u,k)*getitem(v,k) 131 | return s 132 | 133 | def scalar_mul(v, alpha): 134 | """ 135 | Returns the scalar-vector product alpha times v. 136 | 137 | >>> zero = Vec({'x','y','z','w'}, {}) 138 | >>> u = Vec({'x','y','z','w'},{'x':1,'y':2,'z':3,'w':4}) 139 | >>> 0*u == zero 140 | True 141 | >>> 1*u == u 142 | True 143 | >>> 0.5*u == Vec({'x','y','z','w'},{'x':0.5,'y':1,'z':1.5,'w':2}) 144 | True 145 | >>> u == Vec({'x','y','z','w'},{'x':1,'y':2,'z':3,'w':4}) 146 | True 147 | """ 148 | u=v.copy() 149 | for k in v.D: 150 | setitem(u,k, alpha*getitem(v,k)) 151 | return u 152 | 153 | def neg(v): 154 | """ 155 | Returns the negation of a vector. 156 | 157 | >>> u = Vec({2,4,6,8},{2:1,4:2,6:3,8:4}) 158 | >>> -u 159 | Vec({8, 2, 4, 6},{8: -4, 2: -1, 4: -2, 6: -3}) 160 | >>> u == Vec({2,4,6,8},{2:1,4:2,6:3,8:4}) 161 | True 162 | >>> -Vec({'a','b','c'}, {'a':1}) == Vec({'a','b','c'}, {'a':-1}) 163 | True 164 | 165 | """ 166 | u=v.copy() 167 | for k in v.D: 168 | setitem(u,k, -1*getitem(v,k)) 169 | return u 170 | 171 | ############################################################################################################################### 172 | 173 | class Vec: 174 | """ 175 | A vector has two fields: 176 | D - the domain (a set) 177 | f - a dictionary mapping (some) domain elements to field elements 178 | elements of D not appearing in f are implicitly mapped to zero 179 | """ 180 | def __init__(self, labels, function): 181 | self.D = labels 182 | self.f = function 183 | 184 | __getitem__ = getitem 185 | __setitem__ = setitem 186 | __neg__ = neg 187 | __rmul__ = scalar_mul #if left arg of * is primitive, assume it's a scalar 188 | 189 | def __mul__(self,other): 190 | #If other is a vector, returns the dot product of self and other 191 | if isinstance(other, Vec): 192 | return dot(self,other) 193 | else: 194 | return NotImplemented # Will cause other.__rmul__(self) to be invoked 195 | 196 | def __truediv__(self,other): # Scalar division 197 | return (1/other)*self 198 | 199 | __add__ = add 200 | 201 | def __radd__(self, other): 202 | "Hack to allow sum(...) to work with vectors" 203 | if other == 0: 204 | return self 205 | 206 | def __sub__(a,b): 207 | "Returns a vector which is the difference of a and b." 208 | return a+(-b) 209 | 210 | __eq__ = equal 211 | 212 | def is_almost_zero(self): 213 | s = 0 214 | for x in self.f.values(): 215 | if isinstance(x, int) or isinstance(x, float): 216 | s += x*x 217 | elif isinstance(x, complex): 218 | s += x*x.conjugate() 219 | else: return False 220 | return s < 1e-20 221 | 222 | def __str__(v): 223 | "pretty-printing" 224 | D_list = sorted(v.D, key=repr) 225 | numdec = 3 226 | wd = dict([(k,(1+max(len(str(k)), len('{0:.{1}G}'.format(v[k], numdec))))) if isinstance(v[k], int) or isinstance(v[k], float) else (k,(1+max(len(str(k)), len(str(v[k]))))) for k in D_list]) 227 | s1 = ''.join(['{0:>{1}}'.format(str(k),wd[k]) for k in D_list]) 228 | s2 = ''.join(['{0:>{1}.{2}G}'.format(v[k],wd[k],numdec) if isinstance(v[k], int) or isinstance(v[k], float) else '{0:>{1}}'.format(v[k], wd[k]) for k in D_list]) 229 | return "\n" + s1 + "\n" + '-'*sum(wd.values()) +"\n" + s2 230 | 231 | def __hash__(self): 232 | "Here we pretend Vecs are immutable so we can form sets of them" 233 | h = hash(frozenset(self.D)) 234 | for k,v in sorted(self.f.items(), key = lambda x:repr(x[0])): 235 | if v != 0: 236 | h = hash((h, hash(v))) 237 | return h 238 | 239 | def __repr__(self): 240 | return "Vec(" + str(self.D) + "," + str(self.f) + ")" 241 | 242 | def copy(self): 243 | "Don't make a new copy of the domain D" 244 | return Vec(self.D, self.f.copy()) 245 | -------------------------------------------------------------------------------- /voting_record_dump109.txt: -------------------------------------------------------------------------------- 1 | Akaka D HI -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 0 0 1 -1 -1 1 -1 1 -1 1 1 -1 2 | Alexander R TN 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 0 1 1 3 | Allard R CO 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 4 | Allen R VA 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 5 | Baucus D MT -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 0 1 1 1 1 1 1 1 -1 1 0 1 1 -1 1 1 1 6 | Bayh D IN 1 -1 1 1 1 1 -1 1 1 1 1 1 1 1 -1 0 1 1 -1 1 1 1 1 1 -1 1 1 -1 1 1 1 1 1 1 1 0 1 -1 1 -1 1 1 -1 1 1 -1 7 | Bennett R UT 1 1 1 1 1 1 1 1 1 1 1 1 1 0 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 8 | Biden D DE -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 9 | Bingaman D NM 1 0 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 10 | Bond R MO 1 1 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1 1 1 1 1 1 -1 -1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 95 | Thune R SD 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 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 96 | Vitter R LA 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 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 97 | Voinovich R OH 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 98 | Warner R VA 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 99 | Wyden D OR -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 100 | --------------------------------------------------------------------------------