Initial commit - Exercise 1
This commit is contained in:
commit
484fd91f86
|
@ -0,0 +1,25 @@
|
|||
class recipe:
|
||||
def __init__(self, ingredients, standardPortions):
|
||||
self.ingredients = ingredients
|
||||
self.standardPortions = standardPortions
|
||||
|
||||
def getIngredients(self, portions):
|
||||
ratio = portions / self.standardPortions
|
||||
for ingredient in self.ingredients:
|
||||
print(f'{ingredient}: {self.ingredients[ingredient]*ratio}')
|
||||
|
||||
cookies = recipe(
|
||||
ingredients={
|
||||
'sukker(g)': 400,
|
||||
'smør(g)': 320,
|
||||
'sjokolade(g)': 500,
|
||||
'egg': 2,
|
||||
'hvetemel(g)': 460
|
||||
},
|
||||
standardPortions=48,
|
||||
)
|
||||
|
||||
cookieNumber = int(input('Hvor mange cookies ønsker du å bake? '))
|
||||
|
||||
print('Antall cookies:', cookieNumber)
|
||||
cookies.getIngredients(cookieNumber)
|
|
@ -0,0 +1,62 @@
|
|||
COLUMN_PADDING = 10
|
||||
|
||||
class recipe:
|
||||
def __init__(self, ingredients, standardPortions):
|
||||
self.ingredients = ingredients
|
||||
self.standardPortions = standardPortions
|
||||
|
||||
def toMap(self, portions):
|
||||
ratio = portions / self.standardPortions
|
||||
result = {'Antall cookies': portions}
|
||||
for ingredient in self.ingredients:
|
||||
result[ingredient] = self.ingredients[ingredient]*ratio
|
||||
return result
|
||||
|
||||
|
||||
cookies = recipe(
|
||||
ingredients={
|
||||
'sukker(g)': 400,
|
||||
'smør(g)': 320,
|
||||
'sjokolade(g)': 500,
|
||||
'egg': 2,
|
||||
'hvetemel(g)': 460
|
||||
},
|
||||
standardPortions=48,
|
||||
)
|
||||
|
||||
def columnLength(columnElements):
|
||||
elementLengths = list(map(lambda element: len(str(element)), columnElements))
|
||||
return max(elementLengths) + COLUMN_PADDING
|
||||
|
||||
# lshift colum by column
|
||||
# concatenate columns into rows
|
||||
# foreach row print(row)
|
||||
|
||||
cookieQuestionList = [
|
||||
'Hvor mange cookies vil du lage? ',
|
||||
'Hvor mange cookies vil du lage nå? ',
|
||||
'Hvor mange cookies vil du lage til slutt? '
|
||||
]
|
||||
cookieNumbers = list(map(lambda question: int(input(question)), cookieQuestionList))
|
||||
|
||||
# Make recipe maps from every cookie number
|
||||
cookieList = list(map(lambda cNum: cookies.toMap(cNum), cookieNumbers))
|
||||
# Define columns
|
||||
columns = ['Antall cookies', 'sukker(g)', 'sjokolade(g)']
|
||||
|
||||
rawColumnData = {}
|
||||
for column in columns:
|
||||
rawColumnData[column] = [column]
|
||||
rawColumnData[column].extend(list(map(lambda cookie: cookie[column], cookieList)))
|
||||
|
||||
columnLengths = dict(map(lambda column: (column[0], columnLength(column[1])), rawColumnData.items()))
|
||||
|
||||
formattedColumnData = {}
|
||||
for column in columns:
|
||||
formattedColumnData[column] = []
|
||||
for entry in list(rawColumnData[column]):
|
||||
remainingSpaces = columnLengths[column]
|
||||
formattedColumnData[column].append(str(entry).ljust(remainingSpaces))
|
||||
|
||||
for row in range(0, len(columns) + 1):
|
||||
print(formattedColumnData['Antall cookies'][row] + formattedColumnData['sukker(g)'][row])
|
|
@ -0,0 +1,36 @@
|
|||
|
||||
import math
|
||||
|
||||
# Bump the decimal point up by numberOfDecimal points,
|
||||
# add 0.5 to make floor go from 0-1 to 0.5-1.5,
|
||||
# then add back the decimal points.
|
||||
def myRoundFunction(number, numberOfDecimals):
|
||||
decimalFactor = 10 ** numberOfDecimals
|
||||
return math.floor(number * decimalFactor + 0.5) / decimalFactor
|
||||
|
||||
def removeEmptyDecimals(number):
|
||||
hasEmptyDecimals = (number == int(number))
|
||||
return int(number) if hasEmptyDecimals else number
|
||||
|
||||
def inputTypeCheck(message, type, errorMessage):
|
||||
while True:
|
||||
inputValue = input(message)
|
||||
try:
|
||||
return type(inputValue)
|
||||
except ValueError:
|
||||
print(errorMessage)
|
||||
|
||||
number = inputTypeCheck(
|
||||
message='Gi inn et desimaltall: ',
|
||||
type=float,
|
||||
errorMessage='Beklager, det du skrev inn er ikke et nummer. Prøv igjen\n'
|
||||
)
|
||||
|
||||
numberOfDecimals = inputTypeCheck(
|
||||
message='Antall desimaler i avrunding: ',
|
||||
type=int,
|
||||
errorMessage='Beklager, det du skrev inn er ikke et heltall. Prøv igjen\n'
|
||||
)
|
||||
|
||||
roundedNumber = removeEmptyDecimals(myRoundFunction(number,numberOfDecimals))
|
||||
print(f'Avrundet til {numberOfDecimals} desimal: {roundedNumber}')
|
|
@ -0,0 +1,73 @@
|
|||
import math
|
||||
|
||||
def inputTypeCheck(message, type, errorMessage):
|
||||
while True:
|
||||
inputValue = input(message)
|
||||
try:
|
||||
return type(inputValue)
|
||||
except ValueError:
|
||||
print(errorMessage)
|
||||
|
||||
def removeEmptyDecimals(number):
|
||||
hasEmptyDecimals = (number == int(number))
|
||||
return int(number) if hasEmptyDecimals else number
|
||||
|
||||
def myRoundFunction(integerPart,decimalPart,amountOfDecimals):
|
||||
decimalOffset = len(str(integerPart))
|
||||
roundOffset = decimalOffset + amountOfDecimals
|
||||
numberString = f'{integerPart}{decimalPart}'
|
||||
|
||||
lastDigit = int(numberString[roundOffset-1])
|
||||
firstEvalDigit = int(numberString[roundOffset])
|
||||
|
||||
addPointAtOffset = lambda num,off: float(str(num)[:off] + '.' + str(num)[off:])
|
||||
|
||||
if (firstEvalDigit < 5):
|
||||
return addPointAtOffset(numberString[:roundOffset], decimalOffset)
|
||||
|
||||
elif (firstEvalDigit == 5):
|
||||
try:
|
||||
hasDigitsBehind5 = (int(numberString[roundOffset+1:]) > 0)
|
||||
except ValueError:
|
||||
hasDigitsBehind5 = False
|
||||
|
||||
# This is the special case where round() rounds 2.5 down to 2.
|
||||
# It is only valid when there's no digits behind the eval digit
|
||||
# and when the base digit is even.
|
||||
specialCase = ((not hasDigitsBehind5) and (lastDigit % 2 == 0))
|
||||
roundedNumber = int(numberString[:roundOffset]) + 1 - specialCase
|
||||
|
||||
return addPointAtOffset(roundedNumber, decimalOffset)
|
||||
|
||||
else:
|
||||
return addPointAtOffset(int(numberString[:roundOffset]) + 1, decimalOffset)
|
||||
|
||||
def main():
|
||||
integerPart = inputTypeCheck(
|
||||
message='Oppgi heltallsdelen av tallet (det foran punktum): ',
|
||||
type=int,
|
||||
errorMessage='Beklager, det du skrev inn er ikke et heltall. Prøv igjen\n'
|
||||
)
|
||||
|
||||
decimalPart = inputTypeCheck(
|
||||
message='Oppgi desimaldelen av tallet (det bak punktum): ',
|
||||
type=int,
|
||||
errorMessage='Beklager, dette er ikke et tall, eller inneholder et desimalpunkt. Prøv igjen\n'
|
||||
)
|
||||
|
||||
amountOfDecimals = inputTypeCheck(
|
||||
message='Oppgi ønsket antall desimaler i avrunding: ',
|
||||
type=int,
|
||||
errorMessage='Beklager, det du skrev inn er ikke et heltall. Prøv igjen\n'
|
||||
)
|
||||
|
||||
roundedNumber = removeEmptyDecimals(myRoundFunction(integerPart, decimalPart, amountOfDecimals))
|
||||
|
||||
print(f'{integerPart}.{decimalPart} avrundet til {amountOfDecimals} desimaler blir {roundedNumber}')
|
||||
|
||||
def test():
|
||||
print(myRoundFunction(2, 5, 0))
|
||||
print(myRoundFunction(2, 15, 1))
|
||||
print(myRoundFunction(2, 500000000000000000001, 0))
|
||||
|
||||
main()
|
|
@ -0,0 +1,14 @@
|
|||
def getName():
|
||||
while True:
|
||||
name = input('Jeg heter: ')
|
||||
if (' ' in name):
|
||||
return name.split(' ')
|
||||
print('Putt et mellomrom mellom fornavn og etternavn')
|
||||
|
||||
capitalize = lambda name: name.capitalize()
|
||||
|
||||
names = list(map(capitalize, getName()))
|
||||
firstNames = ' '.join(names[:-1])
|
||||
lastName=names[-1]
|
||||
|
||||
print(f'The name is {lastName}, {firstNames} {lastName}')
|
|
@ -0,0 +1,17 @@
|
|||
from math import sqrt
|
||||
|
||||
class Tetraeder:
|
||||
def __init__(self, length):
|
||||
self.length = length
|
||||
self.a = 3/sqrt(6) * length
|
||||
|
||||
getArea = lambda self: sqrt(3) * (self.a**2)
|
||||
getVolume = lambda self: sqrt(2) * (self.a**3) / 12
|
||||
|
||||
figure1 = Tetraeder(3)
|
||||
print(f'Et tetraeder med høyde {figure1.length} har areal {figure1.getArea()}')
|
||||
print(f'Et tetraeder med høyde {figure1.length} har volum {figure1.getVolume()}')
|
||||
print()
|
||||
|
||||
figure2 = Tetraeder(float(input('Skriv inn en høyde: ')))
|
||||
print(f'Et tetraeder med høyde {figure1.length} har volum {figure2.getVolume()} og areal {figure2.getArea()}')
|
Loading…
Reference in New Issue