TDT4109/Exercise 1/10 - Bakekurs/task10b.py

80 lines
2.3 KiB
Python
Raw Normal View History

2020-08-31 23:15:39 +02:00
from typing import List, Dict, Union
from common import inputTypeCheck
2020-08-26 14:47:36 +02:00
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,
)
2020-08-31 23:15:39 +02:00
columnsToPrint = ['Antall cookies', 'sukker(g)', 'sjokolade(g)']
questionList = [
2020-08-26 14:47:36 +02:00
'Hvor mange cookies vil du lage? ',
'Hvor mange cookies vil du lage nå? ',
'Hvor mange cookies vil du lage til slutt? '
]
2020-08-31 23:15:39 +02:00
ask = lambda question: inputTypeCheck(
message=question,
type=float,
errorMessage='Beklager, det du skrev inn er ikke et tall. Prøv igjen\n'
)
cookieAmounts = list(map(ask, questionList))
cookieObjects = list(map(lambda cNum: cookies.toMap(cNum), cookieAmounts))
def createColumns(columnsToPrint) -> Dict[str, List[Union[str, int]]]:
rawColumnData = {}
for column in columnsToPrint:
rawColumnData[column] = [column]
recipeRows = list(map(lambda cookie: cookie[column], cookieObjects))
rawColumnData[column].extend(recipeRows)
return rawColumnData
rawColumns = createColumns(columnsToPrint)
def getColumnLength(column, padding) -> int:
lengths = list(map(lambda element: len(str(element)), column))
return max(lengths) + padding
2020-08-26 14:47:36 +02:00
2020-08-31 23:15:39 +02:00
def formatRows(column) -> List[str]:
columnLength = getColumnLength(column, COLUMN_PADDING)
formattedColumn = []
for entry in column:
formattedColumn.append(str(entry).ljust(columnLength))
return formattedColumn
2020-08-26 14:47:36 +02:00
2020-08-31 23:15:39 +02:00
def formatColumns(unFormattedColumns, columnsToPrint) -> Dict[str, List[str]]:
formattedColumns = {}
for column in columnsToPrint:
formattedColumns[column] = formatRows(unFormattedColumns[column])
return formattedColumns
2020-08-26 14:47:36 +02:00
2020-08-31 23:15:39 +02:00
formattedColumns = formatColumns(rawColumns, columnsToPrint)
2020-08-26 14:47:36 +02:00
2020-08-31 23:15:39 +02:00
for row in range(0, len(formattedColumns['Antall cookies'])):
thisRow=[]
for column in formattedColumns:
thisRow.append(formattedColumns[column][row])
print(''.join(thisRow))