TDT4109/Exercise 5/task8.py

131 lines
3.9 KiB
Python
Raw Normal View History

2020-10-07 13:13:24 +02:00
from common.inputChecking.typeCheck import validateInput as validateTypeInput
from common.inputChecking.boolInput import validateInput as validateBoolInput
from json import dumps as serialize
from json import loads as unserialize
from os.path import isfile
class ExitError(Exception):
pass
def boolInput(question, yesNoLetters=('j','n'), exitKeyword='hade'):
yesLetters = [yesNoLetters[0], yesNoLetters[0].capitalize()]
while True:
answer = input(question)
if answer == exitKeyword:
raise ExitError
if validateBoolInput(answer, yesNoLetters):
return answer in yesLetters
def inputTypeCheck(question, type, exitKeyword='hade'):
while True:
userInput = input(question)
if userInput == exitKeyword:
raise ExitError
if validateTypeInput(userInput, type):
return userInput
class DataSchema:
def __init__(
self,
genderIsMale = None,
age = None,
hasMultipleSubjects = None,
hasITGK = None,
avgStudyTime = None
):
self.genderIsMale = genderIsMale
self.age = age
self.hasMultipleSubjects = hasMultipleSubjects
self.hasITGK = hasITGK
self.avgStudyTime = avgStudyTime
class Survey:
def __init__(self, savePath='./results.json', resultsPath=''):
self.savePath = savePath
if resultsPath != '':
self.resultsPath = resultsPath
self.loadResults()
results = []
def loadResults(self):
try:
file = open(self.resultsPath, 'r')
dicts = unserialize(file.read())
self.results = [DataSchema(**dict) for dict in dicts]
except FileNotFoundError:
print('Fant ikke undersøkelsesdata ved', self.resultsPath)
except Exception as e:
print('Noe gikk galt under lasting av undersøkelsesdata')
print(e)
def printStats(self):
print('Resultat av undersøkelse!')
men = women = multipleChoice = itgk = studyHours = 0
for result in self.results:
if result.genderIsMale:
men += 1
else:
women += 1
multipleChoice += 1 if result.hasMultipleSubjects else 0
itgk += 1 if result.hasITGK else 0
studyHours += int(result.avgStudyTime)
print("Antall kvinner:", women)
print("Antall menn:", men)
print("Antall personer som tar fag:", multipleChoice)
print("Antall personer som tar ITGK:", itgk)
print("Antall timer i snitt brukt på lekser:", studyHours/len(self.results))
def saveResults(self):
serializedResults = serialize([result.__dict__ for result in self.results])
# Check whether file exists
try:
assert not isfile(self.savePath)
except:
if not boolInput(f'Det eksisterer allerede en fil ved {self.savePath}\nVil du overskrive filen? [j/n]: '):
return
# Try to write data to file.
try:
file = open(self.savePath, "w")
file.write(serializedResults)
file.close()
except:
if boolInput('Noe gikk galt under lagring av data. Vil du prøve igjen? [j/n]: '):
self.saveResults()
def end(self):
if len(self.results) > 0:
self.printStats()
self.saveResults()
exit(0)
def update(self):
schema = DataSchema()
print('Velkommen til spørreundersøkelsen!\n')
try:
schema.genderIsMale = boolInput('Hvilket kjønn er du? [f/m]: ', yesNoLetters=('m','f'))
schema.age = inputTypeCheck('Hvor gammel er du?: ', int)
schema.hasMultipleSubjects = boolInput('Tar du et eller flere fag? [j/n]: ')
hasITGKQuestion = 'Tar du ITGK? [j/n]: ' if int(schema.age) < 22 else 'Tar du virkelig ITGK? [j/n]: '
schema.hasITGK = boolInput(hasITGKQuestion)
schema.avgStudyTime = inputTypeCheck('Hvor mange timer bruker du daglig (i snitt) på lekser?: ', float)
self.results.append(schema)
except ExitError:
self.end()
print()
def loop(self):
while True:
self.update()
if __name__ == "__main__":
survey = Survey(resultsPath='./results.json')
survey.loop()