Fasit / Løsningsforslag¶
Uke 2¶
Oppgave 1
navn = input("Hva heter du? ")
print(navn)
print(len(navn))
Oppgave 2
alder = input("Hvor gammel er du? ")
print("Du blir 100 år om", 100-int(alder), "år.")
Oppgave 3
F = float(input("Temperatur i Fahrenheit: "))
print("Temperatur i Celsius:", (F - 32) * 5/9)
Oppgave 4
tekst = input("Tekst: ")
len_box = len(tekst) + 4
print("=" * len_box)
print("=", tekst, "=")
print("=" * len_box)
Oppgave 5
tekst = input("Tekst: ")
tall = int(input("Tall: "))
mellomrom = tall - (len(tekst) + 4)
mellomrom_venstre = mellomrom // 2
mellomrom_høyre = mellomrom - mellomrom_venstre
print("=" * tall)
print("=", " " * mellomrom_venstre + tekst + " " * mellomrom_høyre, "=")
print("=" * tall)
Uke 3¶
Oppgave 1
from math import sqrt
def side_length(x1, y1, x2, y2):
"""Returns the length of the side between the points (x1,y1) and (x2,y2)"""
return sqrt((x2 - x1)**2 + (y2 - y1)**2)
def mid(pointA, pointB, pointC, a, b, c):
"""
Returns midpoint coordinate given:
coordinates pointA, pointB, pointC
sidelengths a, b, c
"""
return (pointA*a + pointB*b + pointC*c) / (a + b + c)
def incircle_radius(a, b, c):
"""Returns the radius of the incircle of a triangle with sidelengths a, b and c"""
s = (a + b + c) / 2
return sqrt(((s-a)*(s-b)*(s-c))/s)
def find_incircle(x1, y1, x2, y2, x3, y3):
"""
Finds and prints the center and radius of the incircle
of a triangle with corners (x1,y1), (x2,y2), (x3,y3)
"""
print(f"Your triangle is ({x1}, {y1}), ({x2}, {y2}), ({x3}, {y3})\n")
print("First we calculate the sidelengths")
side1 = side_length(x1, y1, x2, y2)
side2 = side_length(x2, y2, x3, y3)
side3 = side_length(x3, y3, x1, y1)
print("Then we find the center:")
center_x = mid(x1, x2, x3, side2, side3, side1)
center_y = mid(y1, y2, y3, side2, side3, side1)
print(f"The center is {center_x, center_y}\n")
print("Finally the radius of the incircle:")
radius = incircle_radius(side1, side2, side3)
print(f"The incircle has radius {radius}")
print("Define your triangle:")
x1 = int(input("x1= "))
x2 = int(input("x2= "))
x3 = int(input("x3= "))
y1 = int(input("y1= "))
y2 = int(input("y2= "))
y3 = int(input("y3= "))
find_incircle(x1, y1, x2, y2, x3, y3)
Oppgave 2
def egen_max(a, b):
max = (a + b + abs(a - b))//2
return max
def egen_min(a, b):
min = (a + b - abs(a - b))//2
return min
a = input("Tall 1: ")
b = input("Tall 2: ")
a = int(a)
b = int(b)
print()
print("egen_max(", a, ",", b, ") =", egen_max(a, b))
print("max(", a, ",", b, ") =", max(a, b))
print()
print("egen_min(", a, ",", b, ") =", egen_min(a, b))
print("min(", a, ",", b, ") =", min(a, b))
Oppgave 3
def fahrenheit_til_celsius(temp):
return (temp - 32)*5/9
def celsius_til_fahrenheit(temp):
return temp*9/5 + 32
temp_F = int(input("Gi en temperatur i Fahrenheit: "))
temp_C = fahrenheit_til_celsius(temp_F)
print("Temperatur i Celsius:", round(temp_C, 1))
temp_F_2 = celsius_til_fahrenheit(temp_C)
print("Temperatur i Fahrenheit:", round(temp_F_2, 1))
Oppgave 4
def tegne_boks_rund(tekst):
len_box = len(tekst) + 4
print("=" * len_box)
print("=", tekst, "=")
print("=" * len_box)
navn = input("Hva heter du? ")
print()
tegne_boks_rund(navn)
print()
print("Jeg håper du får en fin dag!")
Uke 4¶
Oppgave 1
def poly_string(a, b, c):
poly = ""
if a == 1:
poly += "x^2"
elif a != 0:
poly += f"{a}x^2"
if b == 1:
if poly:
poly += " + "
poly += "x"
elif b != 0:
if poly:
poly += " + "
poly += f"{b}x"
if c != 0:
if poly:
poly += " + "
poly += f"{c}"
if not poly:
poly = "0"
return poly
if __name__ == "__main__":
a = int(input("Angi koeffisient foran x^2: "))
b = int(input("Angi koeffisient foran x: "))
c = int(input("Angi konstantterm: "))
print(f"Ditt polynom er {poly_string(a, b, c)}.")
Oppgave 2
def poly_string(a, b, c):
poly = ""
if a == 1:
poly += "x^2"
elif a == -1:
poly += "-x^2"
elif a != 0:
poly += f"{a}x^2"
if b == 1:
if poly:
poly += " + "
poly += "x"
elif b == -1:
if poly:
poly += " - x"
else:
poly += "-x"
elif b > 1:
if poly:
poly += " + "
poly += f"{b}x"
elif b < -1:
if poly:
poly += f" - {abs(b)}x"
else:
poly += f"{b}x"
if c > 0:
if poly:
poly += " + "
poly += f"{c}"
elif c < 0:
if poly:
poly += f" - {abs(c)}"
else:
poly += f"{c}"
if not poly:
poly = "0"
return poly
if __name__ == "__main__":
a = int(input("Angi koeffisient foran x^2: "))
b = int(input("Angi koeffisient foran x: "))
c = int(input("Angi konstantterm: "))
print(f"Ditt polynom er {poly_string(a, b, c)}.")
Oppgave 3
def wavelength_to_color(w):
if 380 <= w <= 450:
color = "fiolett"
elif 450 < w <= 485:
color = "blå"
elif 485 < w <= 500:
color = "cyan"
elif 500 < w <= 565:
color = "grønn"
elif 565 < w <= 590:
color = "gul"
elif 590 < w <= 625:
color = "oransje"
elif 625 < w <= 740:
color = "rød"
return color
def frequency_to_color(f):
if 680 < f <= 790:
color = "fiolett"
elif 620 < f <= 680:
color = "blå"
elif 600 < f <= 620:
color = "cyan"
elif 530 < f <= 600:
color = "grønn"
elif 510 < f <= 530:
color = "gul"
elif 480 < f <= 510:
color = "oransje"
elif 405 <= f <= 480:
color = "rød"
return color
if __name__ == "__main__":
unit = input("Hvilken enhet vil du bruke? Svare med 'nm' eller 'THz': ")
if unit == "nm":
value = int(input("Angi en verdi i nm: "))
color = wavelength_to_color(value)
print(f"Lys med bølgelengden {value} nm har fargen {color}.")
elif unit == "THz":
value = int(input("Angi en verdi i THz: "))
color = frequency_to_color(value)
print(f"Lys med frekvensen {value} THz har fargen {color}.")
Oppgave 4
def is_leap_year(year):
if (year % 4 == 0 and not year % 100 == 0) or year % 400 == 0:
leap = True
else:
leap = False
return leap
if __name__ == "__main__":
year = int(input("Angi et årtall: "))
if is_leap_year(year):
print(f"År {year} er et skuddår.")
else:
print(f"År {year} er ikke et skuddår.")
Uke 5¶
Oppgave 1-9
# TASK 1 - many ways to solve, below are 2 example solns
# opt 1
x = 5 #start
while x <= 25: #test
if x % 2 == 0:
print(x)
x += 1 #update
# opt 2
x = 5 # start
while x in range(5,24+1): #test (using +1 to force end into range calc)
if x % 2 == 0:
print(x)
x += 1 #update
#################################
# TASK 2
while True:
answer = input('Hei! Vil du prate med meg? ')
if answer == 'Nei':
break
print('Så kult!')
print('Ha det bra!')
#################################
# TASK 3: for loop writing out 3,6,9,12,15 [loads of ways to solve]
## opt 1
for x in range(3,15+1,3):
print(x)
## opt 2
for x in range(15+1):
if (x % 3 ==0):
print(x)
else:
continue
## opt 3 - BONUS list comprehension
[x for x in range(3,15+1) if x % 3 == 0]
#################################
# TASK 4 : If statement with for or while-loop (your choice). Lots of ways to do this, some possibilities below.
# opt 1 - for loop
for x in range(1,10+1): #force to skip 0 by defining start and end of range
if (x % 2 == 0):
print(f'{x} er partall!')
else:
print(f'{x} er oddetall!')
# opt 2 - another for loop
for x in range(10+1): #don't have 0 in range def but add as statement check in loop
if x == 0:
continue
elif x % 2 == 0:
print(f'{x} er partall!')
else:
print(f'{x} er oddetall!')
# opt 3 - while loop
x = 1 #start
while x <= 10: #test
if (x % 2 == 0):
print(f'{x} er partall!')
else:
print(f'{x} er oddetall!')
x += 1 #update
#################################
# TASK 5: while loop - factorial
number = int(input("Tall: ")) #start
accumulator = 1
if (number == 0):
print(1)
else:
while 1 < number: # test
# print(f'current number is {number}')
accumulator = accumulator * number
# print(accumulator)
number -= 1 #update
print(accumulator)
#################################
# TASK 6 : While-loop
# Print this pattern using a while-loop
star = 1
while star <= 4:
print('*' * star)
star += 1
#################################
# TASK 7 : For-loop
# Print the same pattern with a for loop
for n in range(1, 5):
print('*' * n)
#################################
# TASK 8 : For-loop
# Print a countdown and LIFTOFF!
for i in range(10, 0, -1):
print(i)
print("LIFTOFF!")
#################################
# TASK 9 : For-loop
# Print the letters of "oppvaskmaskin"
for letter in "oppvaskmaskin":
print(letter)
Oppgave 10
def is_pytag(a,b,c):
return a**2 + b**2 == c**2
# Option 1
def pytag_trippel__bruteforce(sum_abc):
for a in range(1, sum_abc):
for b in range(a + 1, sum_abc):
c = sum_abc - a - b
if (0 < a < b < c) and is_pytag(a, b, c):
return a * b * c
return -1
# Option 2
def pytag_trippel__calculated_limits(sum_abc):
for a in range(1, sum_abc // 3):
for b in range(a + 1, (sum_abc - a + 1) // 2):
c = sum_abc - a - b
if is_pytag(a, b, c):
return a * b * c
return -1
# Use option 2 to appease the test
def pytag_trippel(sum_abc):
return pytag_trippel__calculated_limits(sum_abc)
Uke 6¶
Oppgave 1-10
# Oppgave 1
numbers = [0, 7, 97, 7, 5, 7, 20, 11] #start
i = 0 #start
while i < len(numbers): #test
if numbers[i] == 7:
numbers.remove(7)
i += 1 #update
print(numbers)
# Oppgave 2
myList = ['a', 1, 'b', 'c', 2, 6, 'g']
# one method
sliced_list = myList[1:6:2]
print(sliced_list)
# second method
slice_step = slice(1,6,2) #start at index 1, take out up to index 6, alternate indices in list
sliced_list = myList[slice_step]
print(sliced_list)
# Oppgave 3
myList = ['a', 1, 'b', 'c', 2, 6, 'g']
print(myList[::-1])
# Oppgave 4
word = 'bryggeriet'
evens = [] #create empty array to store letters that I extract
for index, letter in enumerate(word):
if index % 2 == 0:
evens += letter #add even-index letter to array
#print(evens) #check
joined = ''.join(evens) #join letters in array back together to form a new word
print(joined)
#faster way to do the same thing
evens = '' #create empty string to store letters that I extract
for index, letter in enumerate(word):
if index % 2 == 0:
evens += letter #add even-index letter to array
print(evens)
# Oppgave 5
word = 'bryggeriet'
lc_evens = [letter for index, letter in enumerate(word) if index % 2 == 0]
print(''.join(lc_evens))
# Oppgave 6
# multiply all numbers in a list by 2 and store in a new list called ``doubled_list```
myList = [1,2,3,4]
doubled_list = []
for item in myList:
doubled_item = item * 2
doubled_list.append(doubled_item)
print(doubled_list)
# Oppgave 7
# from sample list return list with uniques
myList = [1,1,1,1,2,2,3,3,3,3,4,4,4,5,5]
# method 1 - remove()
for item in myList:
if item in myList:
myList.remove(item)
print(myList)
print(len(myList))
# method 2 - append()
uniques = []
for item in myList:
if item not in uniques:
uniques.append(item)
print(uniques)
print(len(uniques))
# Oppgave 8
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
cols = len(grid[0]) #number of columns
for index in range(cols):
for row in grid[::-1]:
print (row[index], end='')
print()
# alternate solution
# we rotate our array 90 degrees clockwise
# (see this answer: https://stackoverflow.com/questions/8421337/rotating-a-two-dimensional-array-in-python)
for line in zip(*grid[::-1]):
# then we use join to print each line without spaces
print("".join(line))
# Oppgave 9
def my_len(iterable):
n = 0
for _ in iterable:
n += 1
return n
# Oppgave 10
def matching_base(base):
if base == 'A':
return 'T'
elif base == 'T':
return 'A'
elif base == 'C':
return 'G'
elif base == 'G':
return 'C'
def complement(dna_in):
result = ""
for b in dna_in:
# attach new letter in front to get reversed result!
result = matching_base(b) + result
return result
### many many other solutions are possible here... ###
Uke 7¶
Oppgave 1-9
# Oppgave 1
# list comprehension: from a list of names, build a list that contains: (1) the name spelled in reverse, and (2) its length
names = ['Jakob', 'Emma', 'Ola', 'Sondre', 'Maia', 'Emilie', 'Noa']
new = [[name[::-1],len(name)] for name in names]
print(new)
# Oppgave 2
# map(funtion,list)
names = ['Jakob', 'Emma', 'Ola', 'Sondre', 'Maia', 'Emilie', 'Noa']
def flip(item):
return [item[::-1], len(item)]
new = list(map(flip, names))
print(new)
# Oppgave 3
# tuple packing/unpacking
cat = ('aloof', 'meow', 'tuna')
dog = ('friendly', 'woof', 'sausage')
# one way
personality, voice, fav_food = zip(cat,dog)
print(list(personality))
# another way
list(cat)
list(dog)
personality_list= []
personality_list.append(cat[0])
personality_list.append(dog[0])
print(personality_list)
# Oppgave 4
# original tuple
cat = ('aloof', 'meow', 'tuna')
# convert to a list
cat_list = list(cat)
# swap item
cat_list[2] = 'laks'
# flip back to tuple and print
print(tuple(cat_list))
# Oppgave 5
#last in, first out
stack = [3,4,5]
#add to stack
stack.append(6)
stack.append(7)
# can have a print statement here to check your additions
#remove from stack
stack.pop()
stack.pop()
stack.pop()
print(stack)
# Oppgave 6
word_list = []
def pigify(word):
vowels = ['a','e','i','o','u']
if word[0] in vowels:
word += 'way'
return word
else:
for letter in word:
if letter in vowels:
index_pos = word.index(letter) #find index pos of first vowel in the word
return word[index_pos:] + word[:index_pos]+'ay'
# create list of words from user input
while True:
# print('Enter word ' + str(len(word_list) + 1) +
# ' (Or enter nothing to stop.):')
word = input("Enter word: ")
if word == '':
break
word_list += [word] # list concatenation
print()
print('original words:')
print(word_list)
print('words in pig latin:')
print(list(map(pigify,word_list)))
# Oppgave 7
#sorted() with keyword arguments
frukt = ['eple', 'appelsin', 'ananas', 'kokosnøtt', 'banan', 'kirsebær']
print(sorted(frukt, key=len))
# Oppgave 8
def return_change(payment, price):
coins = [20, 10, 5, 1]
difference = payment - price
change = []
for coin in coins:
while difference >= coin:
change += [coin]
difference -= coin
return change
Uke 8¶
Oppgave 1
def door_open(settings):
switch = list(settings)
doors = []
# can any door be opened?
if switch[3] == "0" or switch[8] != "P":
return doors
# should the left door be opened?
if switch[0] == "1" or switch[5] == "1":
doors.append("left")
elif switch[2] == "0" and switch[4] == "1":
doors.append("left")
# should the right door be opened?
if switch[1] == "1" or switch[7] == "1":
doors.append("right")
elif switch[2] == "0" and switch[6] == "1":
doors.append("right")
return doors
if __name__ == "__main__":
for n in range(256):
code_1 = f'{bin(n)[2:].zfill(8)}P'
code_2 = f'{bin(n)[2:].zfill(8)}D'
#print(code_1,code_2)
print(f'"{code_1}" : {door_open(code_1)},')
print(f'"{code_2}" : {door_open(code_2)},')
# should print ["left"]
print(door_open("00010100P"))
Oppgave 2
def collatz_sequence(n):
sequence = [n]
while n > 1:
if n % 2 == 0:
n //= 2
else:
n = 3*n + 1
sequence += [n]
return sequence
def euler_14():
max_len = start_num = 0
for i in range(10_000):
l = len(collatz_sequence(i))
if l > max_len:
max_len, start_num = l, i
return start_num
Oppgave 3
def seat_from_position(chart, row, col):
"""
Find out if seat at given position is available
Update seating chart (in place)
Return string with message if the seat was available or not
"""
price = chart[row - 1][col - 1]
if price == 0:
return "The seat is unavailable. Please choose another option."
else:
chart[row - 1][col - 1] = 0
return (
f"The seat in row {row} and column {col} has been purchased for {price} kr."
)
def seat_from_price(chart, price):
"""
Find available seat given a price
Update seating chart (in place)
Return string with message if there was an available
seat with that price or not
"""
for row, line in enumerate(chart):
for col, seat in enumerate(line):
if seat == price:
chart[row][col] = 0
return f"The seat in row {row + 1} and column {col + 1} has been purchased for {price} kr."
return f"There is no available seat with that price. Please choose another option."
def print_chart(chart):
"""
Print seating chart
"""
print()
for line in chart:
print(f"{line[0]:>2}", end="")
for seat in line[1:]:
print(f"{seat:>3}", end="")
print()
print()
if __name__ == "__main__":
seating_chart = [
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 20, 20, 20, 20, 20, 20, 10, 10],
[10, 10, 20, 20, 20, 20, 20, 20, 10, 10],
[10, 10, 20, 20, 20, 20, 20, 20, 10, 10],
[20, 20, 30, 30, 40, 40, 30, 30, 20, 20],
[20, 30, 30, 40, 50, 50, 40, 30, 30, 20],
[30, 40, 50, 50, 50, 50, 50, 50, 40, 30],
]
print("Welcome! Here you can purchase seats for the theatre.")
print("Below are the prices for all the seats:")
print_chart(seating_chart)
print(
"""You can either specify a seat you would like to purchase,
or you can specify a price you want to pay for your seat.
You can buy as many seats as you like.\n"""
)
while True:
option = input(
"Type [s] to specify a seat, type [p] ito specify a price or type [q] to quit: "
)
if option == "q":
break
elif option == "s":
row = int(input("Please specify row number (1-9): "))
col = int(input("Please specify column number (1-10): "))
print()
print(seat_from_position(seating_chart, row, col))
elif option == "p":
price = int(input("Please specify a price: "))
print()
print(seat_from_price(seating_chart, price))
else:
print("Please type either [s], [p] or [q].")
continue
print()
print("Below is the updated seating chart:")
print_chart(seating_chart)
Oppgave Bonus
"""A function for justifying the margins of a text so that
they are straight.
"""
def line_w_whitespace(words, len_w_one_space, line_len):
"""Add whitespace evenly to a list of words to return
a string of given length.
words: a list of strings
len_w_one_space: an integer, combined length of words
with one space between
line_len: an integer, length of output string
"""
extra_spaces = line_len - len_w_one_space
positions = len(words) - 1
equal_spaces = extra_spaces // positions + 1
remaining_spaces = extra_spaces % positions
for i in range(remaining_spaces):
words[-(i % positions + 2)] += " "
return (" " * equal_spaces).join(words)
def justify(text, line_len):
"""Justify margins of a text to be straight with lines
of given length.
text: a string, the text to be justified
line_len: an integer, the length of the output lines
"""
words = text.split()
if not words:
return ""
current_line = words[:1]
current_len = len(current_line[0])
justified_text = ""
for w in words[1:]:
word_len = len(w)
if current_len + word_len + 1 <= line_len:
current_line.append(w)
current_len += word_len + 1
else:
justified_text += (
line_w_whitespace(current_line, current_len, line_len) + "\n"
)
current_line = [w]
current_len = word_len
justified_text += " ".join(current_line)
return justified_text
if __name__ == "__main__":
text = """Alice was beginning to get very tired of sitting by her sister
on the bank, and of having nothing to do: once or twice she had peeped
into the book her sister was reading, but it had no pictures
or conversations in it, 'and what is the use
of a book,' thought Alice 'without pictures or conversation?'"""
print(justify(text, 60))
Uke 9¶
Oppgave 1
shopping_list = {
"brød": 2,
"pizza": 3,
"poteter": 10,
"kaffe": 1,
"ost": 1,
"epler": 14,
}
print(shopping_list)
Oppgave 2
my_dict = {
0 : 0,
1 : "vafler",
"two" : 2,
5 : 4,
}
my_list = [0, 1, "boller", 4]
print("Dictionary Keys:")
for key in my_dict:
print(key)
print("\nDictionary Values:")
for key in my_dict:
print(my_dict[key])
# alternate solution
# for value in my_dict.values():
# print(value)
print("\nDictionary keys/value:")
for key, value in my_dict.items():
print(key, value)
print("\nList values:")
for element in my_list:
print(element)
print("\nList indices/value:")
for i, e in enumerate(my_list):
print(i, e)
Oppgave 3
in_storage = {
"Ancillary Justice": 1_046,
"The Use of Weapons": 372,
"1984": 5_332,
"The Three-Body Problem": 523,
"A Fisherman of the Inland Sea": 728,
}
while True:
title = input("Tittel: ")
if title:
number = in_storage.get(title, 0)
print(f"Vi har {number} av \"{title}\"\n")
else:
break
Oppgave 4
def collatz_sequence(n):
sequence = [n]
while n > 1:
if n % 2 == 0:
n //= 2
else:
n = 3*n + 1
sequence += [n]
return sequence
collatz_dict = {}
for n in range(1,11):
collatz_dict[n] = collatz_sequence(n)
# alternate solution using dictionary comprehension
collatz_dict = {n:collatz_sequence(n) for n in range(1,11)}
print(collatz_dict)
Oppgave 5
in_storage = {
"Ancillary Justice": 1_046,
"The Use of Weapons": 372,
"1984": 5_332,
"The Three-Body Problem": 523,
"A Fisherman of the Inland Sea": 728,
}
while True:
title = input("Tittel: ")
if title:
number = in_storage.setdefault(title, 10)
print(f"Vi har {number} av \"{title}\"\n")
else:
break
Oppgave 6
cars = {
"Escort" : {
"Brand": "Ford",
"Horsepower": 200,
"Wheels": 4,
"Color": "red"
},
"Beetle" : {
"Brand": "Volkswagen",
"Horsepower": 120,
"Wheels": 4,
"Color": "blue"
},
"Isetta" : {
"Brand": "BMW",
"Horsepower": 50,
"Wheels": 3,
"Color": "green"
},
}
for model in cars:
specs = cars[model]
print(f"The {specs['Brand']} {model} has:\n" \
f"{specs['Wheels']} wheels, {specs['Horsepower']} horsepowers, " \
f"and is {specs['Color']}\n")
Oppgave 7
# inventory.py
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
pass # fill in!
return item_total
#check
total = displayInventory(stuff)
print("Total number of items:", total)
Oppgave 8
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
pass # fill in from task 7!
return item_total
def addToInventory(inventory, addedItems):
pass # your code goes here
inv = addToInventory(inv, dragonLoot)
total = displayInventory(inv)
print("Total number of items:", total)
Oppgave 9
numbers = {
0 : '',
1 : 'one',
2 : 'two',
3 : 'three',
4 : 'four',
5 : 'five',
6 : 'six',
7 : 'seven',
8 : 'eight',
9 : 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
100: 'hundred',
1000: 'thousand',
}
def handle_hundreds(hundreds, rest):
# can only deal with numbers up to 999
# digit value should be between 0 and 9
assert 0 <= hundreds <= 9
if hundreds == 0:
return ''
text = numbers[hundreds] + ' ' + numbers[100]
if rest > 0:
text += ' and '
return text
def handle_1_to_99(n):
if n <= 20:
return numbers[n]
tens, ones = divmod(n,10)
assert tens > 1
text = numbers[10*tens]
if ones:
text += '-' + numbers[ones]
return text
def number_name(n):
if n == 1000:
return 'one thousand'
result = ''
hundreds, rest = divmod(n,100)
assert 0 <= rest < 100
result += handle_hundreds(hundreds, rest)
result += handle_1_to_99(rest)
return result
def all_numbernames(n):
total = 0
for n in range(1,n+1):
name = number_name(n)
# remove spaces and dash
name = name.replace(' ','')
name = name.replace('-','')
total += len(name)
return total
def solve_euler_17():
return all_numbernames(1000)
if __name__ == '__main__':
total = all_numbernames(1000)
print(total)
print(handle_1_to_99(19))
# for i in range(1,30):
# print(num_to_word(i))
# for i in range(90,110):
# print(num_to_word(i))
# for i in range(415,425):
# print(num_to_word(i))
# print(num_to_word(999))
# print(num_to_word(1000))
Uke 10¶
Oppgave 1
def open_file(file_name):
with open(file_name, encoding='utf8') as f:
all_lines = f.read()
return all_lines
if __name__=='__main__' :
print(open_file('../askeladden.txt'))
Oppgave 2
def open_file(file_name):
output = ""
with open(file_name, encoding='utf8') as f:
for line in f:
output += '>>>' + line.strip() + '<<<\n'
return output
if __name__=='__main__' :
print(open_file('../askeladden.txt'))
Oppgave 3
def open_file(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
if __name__=='__main__' :
print(open_file('../askeladden.txt'))
Oppgave 4
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:
if 'lame' in line:
fo.write(line)
if __name__=='__main__' :
r_w_file('../in.txt', 'out.txt')
Oppgave 5
def open_file(file_name):
output = ""
try:
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]
except FileNotFoundError:
output = ""
return output
if __name__=='__main__' :
print(open_file('../askeladden.txt'))
Oppgave 6
def dot_product(A, B):
if len(A) != len(B):
raise ValueError(f"Vectors must have same length, but len(A) = {len(A)} and len(B) = {len(B)}")
return sum([a * b for a, b in zip(A, B)])
Oppgave 7
def add_together(a, b, c, d):
return a + b + c + d
def add_together_safely(x, y, z, w):
try:
return add_together(x, y, z, w)
except TypeError as error:
print(f"Failed with error: {error}")
Oppgave 8
def my_get(dictionary, key, default):
try:
return dictionary[key]
except KeyError:
return default
Oppgave 9
def rename_from_data(filename):
# din kode her
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):
# din kode her
for n in namelist:
rename_from_data(n)
# koden nedover er ikke en del av løsning og
# brukes ikke i automatisk vurdering. Du kan endre eksemplene eller
# legge til input() / print() her om du vil, under if __name__...
if __name__ == "__main__":
print('Trying to rename...')
rename_all(['qwghlm.txt', 'qwerty.txt'])
print('Done.')
# sjekk selv at 2 nye fil ble lagret
Oppgave 10
def read_file(filename):
data = []
with open(filename) as f:
for line in f:
line_data = []
for val in line.split():
line_data.append(int(val))
data.append(tuple(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
if __name__ == "__main__":
data = read_file("VIK_sealevel_2000.txt")
print(data[:5])
annual_avg = average(data)
print(annual_avg)
july_average = average(data, 7)
print(july_average)
for month in range(1,13):
print(f'{month:2} average is {average(data, month):5.1f} cm')
data_2 = add_weekday(data)
print(data_2[:25])
for wd in ['Sat','Sun','Mon','Tue','Wed','Thu','Fri']:
print(f'{wd}: {average_weekday(data_2, wd):5.1f} cm.')
Uke 11¶
Oppgave 1¶
from itertools import combinations
deck = [2,3,4,5,6,7,8,9,10,11]
assert len(deck) == 10
for hand in combinations(deck, 3):
if sum(hand) == 21:
print(hand)
Oppgave 2¶
from datetime import date
def count_sunday_1st():
"""
Return a count of all Sundays that were on the 1st of the month
between 1901-01-01 and 2000-12-31.
"""
count = 0
######## din kode ########
for year in range(1901,2001):
for month in range(1,13):
first = date(year,month,1)
if first.isoweekday() == 7:
count += 1
##########################
return count
if __name__ == "__main__":
print(count_sunday_1st())
if count_sunday_1st() == 171:
print('OK!')
Oppgave 3¶
import random
from collections import Counter
def kast_2():
return random.randint(1,6) + random.randint(1,6)
def kast_n_2(n):
return [ kast_2() for _ in range(n) ]
def print_histo(xs):
ctr = Counter(xs)
all = sum(ctr.values())
for item, count in sorted(ctr.items()):
num_star = (100*count)//all
print(f'{item:2} {"*"*num_star}')
if __name__ == "__main__":
resultat = kast_n_2(1000)
print_histo(resultat)
Oppgave 4¶
# Oppgave 4
# This file should maybe be called "my_stat_lib.py"
# ikke bruk eksisterende Python-funksjoner som heter
# mean median mode max min
def mean(data):
"""
Find the arithmetic mean value of a list of integers.
mean = sum of all elements / length of list
You can assume that data has the right format: [ int, int, ... ]
"""
return sum(data) / len(data)
def median(data):
"""
Find the median value of a list of integers.
median = middle of the sorted values
If the list has an even length, take the mean of the two middle values
You can assume that data has the right format: [ int, int, ... ]
"""
sorted_data = sorted(data)
if len(data) % 2 == 0:
i0 = (len(data) // 2) - 1 # Ex, len(list) is 8, i0 is 3
i1 = i0 + 1 # and i1 is 4
return (sorted_data[i0] + sorted_data[i1]) / 2
else:
return sorted_data[len(data) // 2] # Ex, len(list) is 3, result is 1
def mode(data):
"""
Find the modal value of a list of integers.
mode = the value that is most often in the list
If there are several modes, it's enough to return one of them.
You can assume that data has the right format: [ int, int, ... ]
"""
histogram = {}
for n in data:
histogram[n] = histogram[n] + 1 if n in histogram else 1
max_count = 0
max_n = None
for n, count in histogram.items():
if count > max_count:
max_count = count
max_n = n
return max_n
def mode_v2(data):
"""
Find the modal value of a list of integers.
mode = the value that is most often in the list
If there are several modes, it's enough to return one of them.
You can assume that data has the right format: [ int, int, ... ]
"""
from collections import Counter
histogram = Counter(data)
return histogram.most_common(1)[0][1]
def min(data):
"""
Find the minimum value of a list of integers.
You can assume that data has the right format: [ int, int, ... ]
"""
min_data = data[0]
for x in data[1:]:
if x < min_data:
min_data = x
return min_data
def max(data):
"""
Find the maximum value of a list of integers.
You can assume that data has the right format: [ int, int, ... ]
"""
max_data = data[0]
for x in data[1:]:
if x > max_data:
max_data = x
return max_data
Oppgave 5¶
# start with largest first, to make conversion easy
roman_to_int = {
'M' : 1000,
'CM' : 900,
'D' : 500,
'CD' : 400,
'C' : 100,
'XC' : 90,
'L' : 50,
'XL' : 40,
'X' : 10,
'IX' : 9,
'V' : 5,
'IV' : 4,
'I' : 1
}
def from_roman(roman):
"""Convert a roman number to integer"""
num = 0
while roman:
try:
# if one of the 2-char forms matches, use that
two_chars, rest = roman[:2], roman[2:]
num += roman_to_int[two_chars]
except KeyError:
# otherwise translate one char
one_char, rest = roman[:1], roman[1:]
num += roman_to_int[one_char]
roman = rest
return num
def to_roman(num):
"""Convert an integer to the shortest roman number"""
roman = ''
while num:
for r, i in roman_to_int.items():
# find the first roman letter that fits
# then go back to the while-loop
if num >= i:
num -= i
roman += r
break
return roman
def simplify(roman):
"""Convert a roman number to shortest form"""
return to_roman(from_roman(roman))
def solve_euler_089(filename):
"""
How many characters are saved by converting all roman numbers
in 'filename' to shortest form?
"""
sum_diffs = 0
with open(filename) as f:
for line in f:
roman = line.strip()
len_before = len(roman)
len_after = len(simplify(roman))
sum_diffs += len_before - len_after
return sum_diffs
if __name__ == "__main__":
solution = solve_euler_089('roman.txt')
print(solution)
if solution == 743:
print('OK!')
Uke 12¶
Oppgave 1¶
import csv
def read_first_col(file_name):
with open(file_name, newline='', encoding='iso-8859-1') as csvfile:
osloreader = csv.reader(csvfile, delimiter=' ')
for row in osloreader:
print(row[0])
if __name__=='__main__' :
read_first_col('../2019-06-01_Oslo.csv')
Oppgave 2¶
import csv
def write_to_csv(file_name, rows):
with open(file_name, 'w') as outfile:
csv_writer = csv.writer(outfile)
for row in rows:
csv_writer.writerow(row)
def write_to_csv_alt(file_name, rows):
with open(file_name, 'w') as outfile:
csv_writer = csv.writer(outfile)
csv_writer.writerows(rows)
if __name__ == "__main__":
rows = [
["Come Together", 4, 20, "Lennon/McCartney"],
["Something", 3, 3, "Harrison"],
["Maxwell's Silver Hammer", 3, 27, "Lennon/McCartney"],
["Oh! Darling", 3, 26, "Lennon/McCartney"],
["Octopus's Garden", 2, 51, "Starr"],
["I want you", 7, 47, "Lennon/McCartney"],
]
write_to_csv("Abbey_Road.csv", rows)
Oppgave 3¶
import matplotlib.pyplot as plt
from math import sin
# liste med x-verdier
xs = [n / 10 for n in range(101)]
# 2 ulike lister med y-verdier
ys_1 = [sin(x) for x in xs]
ys_2 = [3 * sin(x) for x in xs]
plt.plot(xs, ys_1, ".y") # gule prikker
plt.plot(xs, ys_2, "-g") # grønn sammenhengende linje
# savefig lagrer filene
plt.savefig("test.png")
plt.savefig("test.pdf")
# interaktivt vindu
plt.show()
Oppgave 4¶
#add subticks to plot
import matplotlib.pyplot as plt
from math import sin
# liste med x-verdier
xs = [n / 10 for n in range(101)]
# 2 ulike lister med y-verdier
ys_1 = [sin(x) for x in xs]
ys_2 = [3 * sin(x) for x in xs]
plt.plot(xs, ys_1, "-.r")
plt.plot(xs, ys_2, "--b")
plt.minorticks_on() #turn on minor ticks on axes
# savefig lagrer filene
plt.savefig("test.png")
plt.savefig("test.pdf")
# interaktivt vindu
plt.show()
Oppgave 5¶
import matplotlib.pyplot as plt
from math import sin
import numpy as np
# liste med x-verdier
xs = [n / 10 for n in range(101)]
# 2 ulike lister med y-verdier
ys_1 = [sin(x) for x in xs]
ys_2 = [3 * sin(x) for x in xs]
plt.plot(xs, ys_1, "-.r")
plt.plot(xs, ys_2, "--b")
# add annotation
plt.annotate(
'Første\ninterseksjonen',
xy=(3.149, -0.002),
xycoords='data',
xytext=(0.4, 0.7),
textcoords='axes fraction',
arrowprops=dict(
facecolor='black',
shrink=0.03),
horizontalalignment='left',
verticalalignment='top',
)
# savefig lagrer filene
#plt.savefig("test.png")
#plt.savefig("test.pdf")
# interaktivt vindu
plt.show()
Oppgave 6¶
import csv count_art = {} with open('Akvakulturregisteret.csv', newline='', encoding='iso-8859-1') as csvfile: akvareader = csv.reader(csvfile, delimiter=';') next(akvareader) # skip header line 1 next(akvareader) # skip header line 2 for row in akvareader: art = row[12] #print(art) count_art.setdefault(art, 0) count_art[art] += 1 for art, number in count_art.items(): print(f"{number:5d} {art}") import csv lats = [] lons = [] with open('Akvakulturregisteret.csv', newline='', encoding='iso-8859-1') as csvfile: akvareader = csv.reader(csvfile, delimiter=';') for row in akvareader: try: lat = float(row[-2]) # latitude is second last lon = float(row[-1]) # longitude is last art = row[12] except ValueError: continue if art == "Laks": lats.append(lat) lons.append(lon) print(lats,lons) # eller plot med matplotlibimport csv lats_fersk = [] lons_fersk = [] lats_salt = [] lons_salt = [] with open('Akvakulturregisteret.csv', newline='', encoding='iso-8859-1') as csvfile: akvareader = csv.reader(csvfile, delimiter=';') for row in akvareader: try: lat = float(row[-2]) # latitude is second last lon = float(row[-1]) # longitude is last vann = row[20] except ValueError: continue if vann == "FERSKVANN": lats_fersk.append(lat) lons_fersk.append(lon) elif vann == "SALTVANN": lats_salt.append(lat) lons_salt.append(lon) try: import matplotlib.pyplot as plt plt.plot(lons_salt,lats_salt,'x') plt.plot(lons_fersk,lats_fersk,'+') plt.show() except (ImportError, ModuleNotFoundError) as e: print(f'Import of matplotlib failed: {e}') print(f'We have {len(lats)} latitudes and {len(lons)} longitudes')import csv lats = [] lons = [] with open('Akvakulturregisteret.csv', newline='', encoding='iso-8859-1') as csvfile: akvareader = csv.reader(csvfile, delimiter=';') for row in akvareader: try: lat = float(row[-2]) # latitude is second last lon = float(row[-1]) # longitude is last except ValueError: continue lats.append(lat) lons.append(lon) try: import matplotlib.pyplot as plt plt.plot(lons,lats,'+') plt.show() except (ImportError, ModuleNotFoundError) as e: print(f'Import of matplotlib failed: {e}') print(f'We have {len(lats)} latitudes and {len(lons)} longitudes')
Uke 13¶
Oppgave 1-9¶
######################
# Oppgave 1
import numpy as np
arr = np.array([[34, 13, 7],
[86, 96, 93],
[72, 47, 42]])
print(arr[1, 2])
######################
# Oppgave 2
import numpy as np
arr = np.array([[34, 13, 7],
[86, 96, 93],
[72, 47, 42]])
print(arr[0:3, 0])
#print(arr[:, 0])
######################
# Oppgave 3
import numpy as np
arr = np.array([[34, 13, 7],
[86, 96, 93],
[72, 47, 42]])
print(arr[1:3, 0:2])
######################
# Oppgave 4
import numpy as np
odds = np.arange(43, 100, 2)
print(odds)
######################
# Oppgave 5
import numpy as np
arr = np.linspace(0,3,9)
print(arr)
######################
# Oppgave 6
import numpy as np
arr = np.arange(1,16)
print(arr.reshape(3,5))
######################
# Oppgave 8
import numpy as np
arr = np.arange(1,16)
print(arr[arr % 2 != 1])
######################
# Oppgave 9
import numpy as np
arr = np.arange(1,16)
arr[arr % 2 != 1] = 0
print(arr)
Oppgave 7¶
import numpy as np
def parabola(a: float, b: float, c: float, xs: np.ndarray):
return a*xs**2 + b*xs + c
if __name__ == "__main__":
import matplotlib.pyplot as plt
xs = np.linspace(-6, 6)
ys = parabola(-1.5, .5, 25, xs)
plt.plot(xs, ys)
plt.grid(alpha=.5, linestyle='--')
# Adds axis to the plot
ax = plt.gca()
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.show()
Oppgave 10¶
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(12)
N_steps = 25*10**4
expected_R = np.sqrt(N_steps) #*2/np.pi)
M = expected_R
K = 7
for i in range(K):
dirs = np.random.randint(0, 4, N_steps)
xs = np.empty((N_steps,2))
xs[dirs == np.uint8(0)] = [0,1]
xs[dirs == np.uint8(1)] = [0,-1]
xs[dirs == np.uint8(2)] = [1,0]
xs[dirs == np.uint8(3)] = [-1,0]
#xs = np.random.choice([[0,1],[1,0],[0,-1],[-1,0]], size=N_steps) #np.random.randint(0, 3, (5*N_steps,2),dtype=np.int32) - 1
#xs = xs[np.abs(xs.sum(axis=1)) == 1][:N_steps]
assert xs.shape[0] == N_steps
xs = xs.cumsum(axis=0)
#print(np.where((xs[:,0] == 0) & (xs[:,1] == 0)))
maxdist = np.sqrt((xs**2).sum(axis=1).max())
skip = N_steps//5000 + 1
plt.plot(xs[::skip,0],xs[::skip,1],'-',label=f"{maxdist =:7.1f}")
minval = abs(xs.min())
maxval = abs(xs.max())
M = max(minval, maxval, M)
plt.xlim(-M,M)
plt.ylim(-M,M)
plt.title(f'{K} random walks of {N_steps} steps')
circ = plt.Circle((0,0), radius=expected_R, color='k')
plt.gcf().gca().add_artist(circ)
plt.gcf().gca().set_aspect('equal')
#plt.legend()
plt.show()
Uke 14¶
Oppgave 1¶
import pandas as pd
import matplotlib.pyplot as plt
# these ones are just for fun to get 12 random colors
from matplotlib.colors import get_named_colors_mapping
from random import sample
def read_data(filename):
data = pd.read_csv(filename, sep=" ",
names=['year', 'month', 'day', 'hour', 'sealevel'])
# subtract one from every hour cause they are 1-24 instead of 0-23
data['hour'] -= 1
# use year, month, day and hour to construct datetime object
data['date'] = pd.to_datetime(data[['year', 'month', 'day', 'hour']])
data = data.set_index('date')
return data
def plot_months(dataframe):
# pick out just sealevel and group by month and hour
sl = dataframe['sealevel']
grouped = sl.groupby([sl.index.month, sl.index.hour]).mean()
# pick 12 random colors
month_color = sample(get_named_colors_mapping().keys(), 12)
grouped.unstack(level=0).plot(color=month_color)
plt.title("Average Sealevel by Month and Time of Day")
plt.xlabel("Time of Day")
plt.ylabel("Sealevel (cm)")
plt.legend(title="Month", ncol=3)
plt.show()
def plot_rolling_average(dataframe, month=6):
sl = dataframe['sealevel']
rolling_avg = sl.rolling('1490min').mean() # 24h50min = one tide cycle
sl[sl.index.month == month].plot(label='Raw Data', alpha=0.4)
rolling_avg[rolling_avg.index.month == month].plot(label='Rolling Average (24h50min)')
plt.ylabel("Sealevel (cm)")
plt.legend()
plt.show()
if __name__ == "__main__":
data = read_data("../VIK_sealevel_2000.txt")
plot_months(data)
plot_rolling_average(data)
Oppgave 2¶
def find_item(garden,item):
for i,line in enumerate(garden):
for j,it in enumerate(line):
if it == item:
return (i,j)
return None
def swap_items(garden1,garden2,pos1,pos2):
i1,j1 = pos1
i2,j2 = pos2
garden1[i1][j1], garden2[i2][j2] = garden2[i2][j2], garden1[i1][j1]
def clean_helper(my_garden, neighbors_garden, plant1, plant2):
while True:
a = find_item(my_garden,plant1)
b = find_item(neighbors_garden,plant2)
if a and b:
swap_items(my_garden,neighbors_garden,a,b)
else:
break
def clean_garden(my_garden, neighbors_garden):
"""
Bytt ut all "rock" med "strawberry", og "moss" med "raspberry" fra naboen sin hage
så lenge det finnes muligheter for bytte.
Args:
my_garden - din hage
neighbors_garden - naboen sin hage
"""
clean_helper(my_garden, neighbors_garden, "rock", "strawberry")
clean_helper(my_garden, neighbors_garden, "moss", "raspberry")
if __name__ == "__main__":
my_garden = [
["grass", "moss"],
["moss", "strawberry"],
["moss","rock"]
]
other_garden = [
["grass", "raspberry"],
["grass", "strawberry"],
["strawberry","rock"]
]
clean_garden(my_garden, other_garden)
my_after = [
['grass', 'raspberry'],
['moss', 'strawberry'],
['moss', 'strawberry']
]
other_after = [
['grass', 'moss'],
['grass', 'rock'],
['strawberry', 'rock']
]
if my_after == my_garden and other_after == other_garden:
print('OK!')
Oppgave 3¶
################
# read in data
################
with open('keylog.txt') as f:
keylog = f.readlines()
keylog = [ line.strip() for line in keylog ]
##################################
# build the required information
##################################
# dict of num -> [num]
# e.g. 3 : [4,5,6] means 4, 5 and 6 come before 3
comes_before = {}
# hard to find a good function name here
def record_item_order(first, second):
"""Register that 'first' comes before 'second'."""
comes_before.setdefault(first,[])
comes_before.setdefault(second,[])
if first not in comes_before[second]:
comes_before[second].append(first)
# always have 3 items, so can unpack directly
for a,b,c in keylog:
# print(a,b,c) # useful while developing
record_item_order(a,b)
record_item_order(a,c)
record_item_order(b,c)
# print(comes_before) # useful while developing
##############################################################
# find the items in the right order, build up solution string
##############################################################
def find_empty_before():
"""
Find the number that has no other numbers listed as coming before.
There should always be one like that, so not finding one is an error.
"""
for num, bef_list in comes_before.items():
# print(num,bef_list) # useful while developing
if bef_list == []: # if not bef_list: # if bef_list.size() == 0:
return num
assert False, "Should not get here"
# -- or --
# print("Should not get here")
# exit(1)
# -- or --
# return None
# loop as long as there are numbers left in the dict
solution = ""
while comes_before: # turns False once dict is empty
next_num = find_empty_before()
solution += next_num
# remove from dict, we dealt with it
del comes_before[next_num]
# remove from lists, makes a new empty list
for k, v in comes_before.items():
v.remove(next_num)
# useful while developing
# print(next_num)
# print(comes_before)
# print(solution)
#################
# present result
#################
print(solution)