Graded Assignment Solutions Week 9 - Python

Subject: Python

Week: 9

Solutions: Graded Assignments


GrPA 1

def get_freq(filename):
    f = open(filename, 'r')
    freq = dict()
    for line in f:
        word = line.strip()
        if word not in freq:
            freq[word] = 0
        freq[word] += 1
    f.close()
    return freq

GrPA 2

def relation(file1, file2):
    f1 = open(file1, 'r')
    L1 = f1.readlines()
    for i in range(len(L1)):
        L1[i] = L1[i].strip()
    f1.close()

    f2 = open(file2, 'r')
    L2 = f2.readlines()
    for i in range(len(L2)):
        L2[i] = L2[i].strip()    
    f2.close()

    if L1 == L2:
        return 'Equal'

    for i in range(len(L1)):
        if L1[i] != L2[i]:
            return 'No Relation'
    return 'Subset'

GrPA 3

def get_goals(filename, country):
    f = open(filename, 'r')
    # Ignore the header
    f.readline()
    nplayers, ngoals = 0, 0
    for line in f:
        # Unpacking a list into three variables
        player, country_file, goals = line.split(',')
        if country_file == country:
            nplayers += 1
            ngoals += int(goals)
    f.close()
    if nplayers > 0:
        return (nplayers, ngoals)
    return (-1, -1)

GrPA 4

def num_to_words(mat):
    P = {0: 'zero', 1: 'one', 2: 'two',
    3: 'three', 4: 'four', 5: 'five',
    6: 'six', 7: 'seven', 8: 'eight',
    9: 'nine'}
    f = open('words.csv', 'w')
    n = len(mat)
    for i in range(n):
        for j in range(n):
            line = f'{P[mat[i][j]]}'
            # do not add a comma for the elements in the last column
            if j != n - 1:
                line += ','
            f.write(line)
        # go to the next line as long as you are not in the last line
        if i != n - 1:
            f.write('\n')    
    f.close()