Comp Sci Prac
Comp Sci Prac
Q1:
A)
>>>num_diffs(‘A’, ‘C’)
1
>>>num_diffs(‘ACTGTGC’, ‘ACTGTGC’)
0
“””
diffs = 0
for i in range(len(dna1)):
if dna1[i] != dna2[i]:
diffs += 1
return diffs
B)
Q2:
A)
Suppose we need to process files where data is stored in the following format blah blah bah
(see q2 f23)
B)
order = {}
line = data_file.readline()
while line != END + ‘\n’:
words = line.strip().split(ITEM_SEP)
order[words[0]] = int(words[1])
line = data_file.readline()
return order
Q3:
A)
B)
Example Answers:
arg = [‘csc’, ‘a08’, ‘is’, ‘csc’, ‘great’, ‘is’, ‘csc’]
original = [‘csc’, ‘a08’, ‘is’, ‘great’, ‘is’, ‘csc’]
make_word_to_count(arg)
msg = (“The function make_word_to_count should not modify its input. \,”
+ “When we called it with argument: \n”
+ str(original)
+ “the input changed to: \n”
+ str(arg))
self.assertEqual(original, arg, msg)
F22
Q1:
A)
>>>get_grades_by_section({})
{}
>>>id_to_info = {1: (‘sec01’, 69), 23: (‘sec02’, 95), 5: (‘sec01’, 82)}
>>>get_grades_by_section(id_to_info) == {‘sec01’: [69, 82], ‘sec02’: [95]}
True
“””
section_to_grades = {}
for info in id_to_grade_info.values():
section = info[SEC_IDX]
grade = info[GRADE_IDX]
if section in section_to_grades:
section_to_grades[section].append(grade)
else:
section_to_grades[section] = [grade]
return section_to_grades
B)
>>>get_average_by_section({})
{}
>>>id_to_info = {1: (‘sec01’, 69), 23: (‘sec02’, 95), 5: (‘sec01’, 82)}
>>>get_average_by_section(id_to_info) == {‘sec01’: 76, ‘sec02’: 95}
True
“””
section_to_grades = get_grades_by_section(id_to_grade_info)
section_to_average = {}
for section in section_to_grades:
grades = section_to_grades[section]
# we know grades is not empty, so safe to divide by len(grades)
section_to_average[section] = math.ceil(sum(grades) / len(grades))
return section_to_average
Q2:
>>>my_sort([], 42)
[]
>>>my_sort([(‘b’, 2), (‘a’, 1)], 1)
[(‘a’, 1), (‘b’, 2)]
“””
sorted_tuples = []
for tup in tuples:
my_insert(tup, sorted_tuples, sort_by)
return sorted_tuples
>>>tuples = []
>>>my_insert((‘g’, 20), tuples, 1)
>>>tuples
[(‘g’, 20)]
>>>my_insert((‘c’, 5), tuples ,1)
>>>tuples
[(‘c’, 5), (‘g’, 20)]
“””
i=0
while i < len(tuples) and tup[sort_by] > tuples[i][sort_by]:
i=i+1
tuples.insert(i, tup)