Uke 10

Oppgave 1

def open_file(file_name):
    with open(file_name, encoding="utf8") as f:
        all_lines = f.read()
    return all_lines

Oppgave 2

def open_file(file_name):
    output = ""
    with open(file_name, encoding="utf8") as f:
        for line in f:
            # output += ">>>" + line.strip() + "<<<\n"  # same as below, without using f-strings
            output += f">>>{line.strip()}<<<\n"
    return output

Oppgave 3

def r_w_file(filename_in, filename_out):
    with open(filename_in, "r") as fi, open(filename_out, "w") as fo:
        for line in fi:
            _, temp = line.split()
            if float(temp) >= 23.5:
                fo.write(line)

Oppgave 4

def first_letter_last_word(file_name):
    output = ""
    with open(file_name, encoding="utf8") as f:
        for line in f:
            word = line.split()
            if word:  # in case the line is blank
                last = word[-1]
                output += last[0]
    return output

Oppgave 5

def first_letter_last_word(filename):
    output = ""
    with open(filename, encoding="utf8") as f:
        for line in f:
            word = line.split()
            if word:  # in case the line is blank
                last = word[-1]
                output += last[0]
    return output


def first_letters(filename):
    try:
        output = first_letter_last_word(filename)
    except FileNotFoundError:
        output = ""
    return output

Oppgave 6

def add_together(a, b, c, d):
    return a + b + c + d


def add_together_safely(x, y, z, w):
    try:
        result = add_together(x, y, z, w)
    except TypeError as error:
        print(f"Failed with error: {error}")
        result = None
    return result

Oppgave 7

def my_get(dictionary, key, default):
    try:
        return dictionary[key]
    except KeyError:
        return default

Oppgave 8

def dot_product(A, B):
    if len(A) != len(B):
        raise ValueError(
            f"Vectors must have same length, but {len(A) = } and {len(B) = }"
        )

    return sum(a * b for a, b in zip(A, B))

Oppgave 9

def rename_from_data(filename):
    with open(filename) as f:
        lines = f.readlines()
    newname = f'{lines[1].strip()}_{lines[0].strip()}.txt'
    with open(newname,'w') as f:
        f.writelines(lines[2:])
        

def rename_all(namelist):
    for n in namelist:
        rename_from_data(n)

Oppgave 10


def read_file(filename):
    data = []
    with open(filename) as f:
        for line in f:
            line_data = tuple( int(val) for val in line.split() )
            data.append(line_data)
    return data


def average(data, month=None):
    measurements = []
    for line in data:
        year, mth, day, hour, height = line
        if month is None or month == mth:
            measurements.append(height)
    return sum(measurements)/len(measurements)


def average_weekday(data, wkd):
    measurements = []
    for line in data:
        year, mth, day, hour, height, weekday = line
        if weekday == wkd:
            measurements.append(height)
    return sum(measurements)/len(measurements)

    
def add_weekday(data):        
    weekdays = ['Sat','Sun','Mon','Tue','Wed','Thu','Fri']
    new_data = []
    for day, line in enumerate(data):
        day //= 24
        day = weekdays[day % 7]
        new_data.append(line + (day,))
    return new_data