CompSciHW6
From Predictive Chemistry
Homework 6 - Due Friday, March 25
1) Create a function that parses the following files: a) mat33 = """ 1.0 2.0 3.0 -2.0 0.0 1.0 1.0 1.1 1.2 """ # output a matrix # example function structure def parse_mat(s): mat = [] # build a list of lists ... return array(mat) # make into an array b) csv = """ # time temperature sea_level 0.0, 300.0, 44.5 1.5, 299.5, 44.0 3.0, 299.8, 44.2 4.5, 301.0, 43.9 """ # output a list of strings and a matrix c) name_val = """ seed = 1553 name = "test name" trials = 10 tolerance = 1e-8 """ # output a dictionary d) group_data = """ [Group 1] 1 2 3 4 5 6 [Group 2] 4 5 11 14 1 [Group 3] 7 8 9 10 11 """ # output a dictionary of [int] 2) Complete this function by adding a for loop to fill each element of a vector with a function (g(i)): from numpy import * def vec_from_func(n, g): # int -> (int -> float) -> array x = zeros(n, float) for ... return x # example call def square_x(x): # int -> float return 1.0*x*x g_arr = vec_from_func(10, square_x) 3) Complete this function by adding a nested for-loop to fill each element of a matrix with a function, u(i,j): from numpy import * def mat_from_func(n,m, g): # int -> int -> (int -> int -> float) -> array M = zeros((n,m), float) for ... for ... return M
Hint:
<source lang="python">
- parse key-value pairs
def get_kv(x): # str -> (str, str)
n = x.find('=') if n < 0: raise ValueError return x[:n].strip(), x[n+1:].strip()
- basic parser structure:
def parse_cif(name):
f = open(name, 'r') out = {} state = 0 vals = [] for line in f.readlines(): k = line.strip() if not k: continue # test whether line contains useful info. return out
</source>