0% found this document useful (0 votes)
13 views8 pages

Comp Sci Prac

The document contains Python code snippets for various functions related to DNA sequence comparison, order processing, and grade management. It includes implementations for calculating differences between DNA sequences, reading orders from files, and aggregating orders by store. Additionally, it features functions for sorting tuples and calculating averages by section from a dictionary of student grades.

Uploaded by

winterluvr420
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views8 pages

Comp Sci Prac

The document contains Python code snippets for various functions related to DNA sequence comparison, order processing, and grade management. It includes implementations for calculating differences between DNA sequences, reading orders from files, and aggregating orders by store. Additionally, it features functions for sorting tuples and calculating averages by section from a dictionary of student grades.

Uploaded by

winterluvr420
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

F23-1:

Q1:

A)

Complete the implementation of the following helper function:

def num_diffs(dna1: str, dna2: str) -> int:


​ “””Return the number of pairs of corresponding elements of DNA sequences
​ dna1 and dna2 that differ.

​ Precondition: dna1 and dna2 have the same length.

​ >>>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)

Complete the implementation of the following function

def closest(dna: str, dnas: list[str]) -> list[str]:


​ “””Return a list of DNA sequences from dnas that are closest (smallest number of
​ corresponding pairs of characters differ) to the DNA sequence dna. Elements in the
​ return list appear in the same order as in the list dnas.

​ Precondition: each element in dnas has the same length as dna

​ >>>closest(‘ACTGTGC’, [‘ACTGTGA”, ‘ACTGTGG’, ‘ACTGTGC’])


​ [‘ACTGTGC’]
​ >>>closest(‘ACTGTGC’, [‘ACTGTAA’, ‘ACTGTGA’, ‘ACTGTGG’])
​ [‘ACTGTGA’, ‘ACTGTGG’]
​ “””
​ result = []
​ smallest_diff = len(dna)
​ for curr_dna in dnas:
​ ​ curr_diff = num_diffs(curr_dna, dna)
​ ​ if curr_diff < smallest_diff:
​ ​ ​ result = [curr_dna]
​ ​ ​ smallest_diff = curr_dna
​ ​ elif curr_diff == smalest_diff:
​ ​ ​ result.append(curr_dna)
​ return result

Q2:

A)

Suppose we need to process files where data is stored in the following format blah blah bah
(see q2 f23)

def read_orders(data_filee: TextIO) -> OrdersType:


​ “””Read the orders info from file data_file and return the corresponding orders

​ Precondition: data_file is open for reading


​ ​ data_file’s position is at the beginning of the file
​ “””
​ orders = {}
​ line = data_file.readline()
​ while line != ‘’:
​ ​ customer_id = line.split(SEP)[0]
​ ​ store = data_file.readline().strip()
​ ​ order = read_order(data_file)
​ ​ orders[customer_id] = (store, order)
​ ​ line = data_file.readline()​
​ return orders

B)

def read_order(data_file: TextIO) -> OrderType:


​ “””Read and return one order from data_file

​ Precondition: data_file is open for reading


​ ​ data_file’s position is at the beginning of the line containing
​ ​ ​ ​ first item of an order
​ “””

​ 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)

Helper function, finish it, add to order:

def ​ add_to_order(order1: OrderType, order2: OrderType) -> None:


​ “””Add all items from order order2 to order order 1.

​ >>>order = {‘Milk’: 1, ‘Gala apples’: 3, ‘Choco’: 1}


​ >>>add_to_order(order, {‘Milk’: 1, ‘Berries’: 3, ‘Choco’: 2})
​ >>>order == {‘Milk’: 2, ‘Gala apples’: 3, ‘Choco’: 3, ‘Berries’: 3}
​ True
​ “””

​ for (name, quantity) in order2.items():


​ ​ if name in order1:
​ ​ ​ order1[name] += quantity
​ ​ else:
​ ​ ​ order1[name] = quantity

B)

def​ orders_by_store(id_to_order: OrdersType) -> dict[str, OrderType]:


​ “””Return a dictionary that maps store name to an OrderType containing all items that
​ need to be purchased at that store, from all orders in id_to_order.
​ >>>orders_by_store(DATA) == DATA_BY_STORE
​ True
​ “””
​ store_to_order = {}
​ for order_info in id_to_order.values():
​ ​ store = order_info[0]
​ ​ order = order_info[1]
​ ​ if store in store_to_order:
​ ​ ​ add_to_order(store_to_order[store], order)
​ ​ else:
​ ​ ​ store_to_order[store] = deepcopy(order)
​ return store_to_order


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)

def get_grades_by_section(id_to_grade_info: dict[int, tuple[str, int]]) -> dict[str, list[int]]:


​ “””Return a dictionary that maps section to a list of grades for that section, using the
information in id_to_grade_info.

​ id_to_grade_info maps student ID to a tuple of two elements (section, grade)

​ >>>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)

def get_average_by_section(id_to_grade_info: dict[int, tuple[str, int]]) -> dict[str, int]:


​ “””Return a dictionary that maps section to the average grade in that
section, using the information in id_to_grade_info

id_to_grade_info maps student ID to a tuple of two elements (section, grade)

>>>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:

def my_sort(tuples: list[tuple], sort_by: int) -> list[tuple]:


​ “””Return tuple sorted by elements at index sort_by

​ >>>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

def my_insert(tup: tuple, tuples: list[tuple], sort_by: int) -> None:


“””Insert tup into tuples at the appropriate position so that tuples remains sorted by
elements at index sort_by.

>>>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)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy