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

80 lines
2.3 KiB
Python

from typing import List, Dict, Union
from common import inputTypeCheck
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,
)
columnsToPrint = ['Antall cookies', 'sukker(g)', 'sjokolade(g)']
questionList = [
'Hvor mange cookies vil du lage? ',
'Hvor mange cookies vil du lage nå? ',
'Hvor mange cookies vil du lage til slutt? '
]
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
def formatRows(column) -> List[str]:
columnLength = getColumnLength(column, COLUMN_PADDING)
formattedColumn = []
for entry in column:
formattedColumn.append(str(entry).ljust(columnLength))
return formattedColumn
def formatColumns(unFormattedColumns, columnsToPrint) -> Dict[str, List[str]]:
formattedColumns = {}
for column in columnsToPrint:
formattedColumns[column] = formatRows(unFormattedColumns[column])
return formattedColumns
formattedColumns = formatColumns(rawColumns, columnsToPrint)
for row in range(0, len(formattedColumns['Antall cookies'])):
thisRow=[]
for column in formattedColumns:
thisRow.append(formattedColumns[column][row])
print(''.join(thisRow))