Graded Assignment Solutions Week 7 - Python

Subject: Python

Week: 7

Solutions: Graded Assignments


GRPA 1

results = [ ]
for i in range(8):
    L = input().split(',')
    winner = L[0]       # the first team is the winner
    losers = L[1: ]     # all these teams have lost to the winner
    # we only need the number of wins and the winning team
    results.append((winner, len(losers)))

table = [ ]
# two-level-sort
# refer GrPA-4 of week-6
# we first sort by points, then by name
while results != [ ]:
    maxteam = results[0]
    for i in range(len(results)):
        team = results[i]
        if team[1] > maxteam[1]:
            maxteam = team
        elif team[1] == maxteam[1] and team[0] < maxteam[0]:
            maxteam = team
    results.remove(maxteam)
    table.append(maxteam)

for team in table:
    print(f'{team[0]}:{team[1]}')

GRPA 2

# The basic idea is to write the code for priority equal to "first"
# When priority is "second", we can just reverse the order of the dicts
def merge(D1, D2, priority):
    if priority == 'second':
        return merge(D2, D1, 'first')
    D = dict()
    # First copy all key-value pairs in D1 to D
    for key in D1:
        value = D1[key]
        D[key] = value
    # Copy all those key-value pairs in D2 to D
    # where the key is not already present in D
    for key in D2:
        value = D2[key]
        if key not in D:
            D[key] = value
    return D

GRPA 3

def minor_matrix(M, i, j):
    # dimension of M
    n = len(M)
    # the matrix M_ij
    M_ij = [ ]
    for row in range(n):
        # skip row i
        if row == i:
            continue
        L = [ ]
        for col in range(n):
            # skip column j
            if col == j:
                continue
            # add all other elements as they are
            L.append(M[row][col])
        M_ij.append(L)
    return M_ij

GRPA 4

n = int(input())
station_dict = dict()

while n > 0:
    train = input()
    num_comps = int(input())
    train_dict = dict()
    for i in range(num_comps):
        comp, count = input().split(',')
        train_dict[comp] = int(count)
    station_dict[train] = train_dict
    n = n - 1