
def union(s1, s2):
    s3 = set()
    for e in s1:
        s3.add(e)
    for e in s2:
        s3.add(e)
    return s3

print(union({1, 2, 3}, {3, 4, 5}))
print(union({'apple', 'orange', 'grape', 'fruit'}, {'apple', 'orange', 'kiwi'} ))

def intersection(s1, s2):
    s3 = set()
    for e in s1:
        if e in s2:
            s3.add(e)
    return s3

print(intersection({1, 2, 3}, {3, 4, 5}))
print(intersection({'apple', 'orange', 'grape', 'fruit'}, {'apple', 'orange', 'kiwi'} ))

# cannot use list, dictionary, count
def one_appearance_names(data):
    many = set()
    one = set()
    sp = data.split(' ')
    for e in sp:
        if e in one:
            one.remove(e)
            many.add(e)
        elif e not in many:
            one.add(e)
    print('--- names ---')
    for e in one:
        print('  ' + e)
    print()

one_appearance_names('joe joe sam sam carly carly alex')
one_appearance_names('joe jim anne annie jim joe annie john james john annie luke annie paul sam')

def average_grade(csv_file, col):
    f = open(csv_file, 'r')
    titles = f.readline().split(',')
    data = []
    for line in f:
        data.append(line.strip('\n').split(','))
    summation = 0
    for row in data:
       summation += int(row[col])
    print('The average grade for ' + titles[col] + ' is ' + str(summation/len(data)))

average_grade('grades.csv', 1)
average_grade('grades.csv', 3)
average_grade('grades.csv', 5)

def group_words(input_file, output_file):
    f = open(input_file, 'r')
    groups = {}
    for line in f:
        line = line.strip('\n').lower()
        first = line[0]
        if first not in groups:
            groups[first] = set()
        groups[first].add(line)
    f = open(output_file, 'w')
    for k, v in groups.items():
        f.write('words beginning with ' + k + ': ' + ' '.join(list(v)) + '\n')
    f.close()

group_words('fruits.txt', 'out1.txt')
group_words('lorem-ipsum.txt', 'out2.txt')


