Compare commits
2 Commits
Author | SHA1 | Date |
---|---|---|
Oystein Kristoffer Tveit | 697f4ab914 | |
Oystein Kristoffer Tveit | e273e2a7d9 |
|
@ -0,0 +1,114 @@
|
|||
# The default ``config.py``
|
||||
# flake8: noqa
|
||||
|
||||
|
||||
def set_prefs(prefs):
|
||||
"""This function is called before opening the project"""
|
||||
|
||||
# Specify which files and folders to ignore in the project.
|
||||
# Changes to ignored resources are not added to the history and
|
||||
# VCSs. Also they are not returned in `Project.get_files()`.
|
||||
# Note that ``?`` and ``*`` match all characters but slashes.
|
||||
# '*.pyc': matches 'test.pyc' and 'pkg/test.pyc'
|
||||
# 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc'
|
||||
# '.svn': matches 'pkg/.svn' and all of its children
|
||||
# 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o'
|
||||
# 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o'
|
||||
prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject',
|
||||
'.hg', '.svn', '_svn', '.git', '.tox']
|
||||
|
||||
# Specifies which files should be considered python files. It is
|
||||
# useful when you have scripts inside your project. Only files
|
||||
# ending with ``.py`` are considered to be python files by
|
||||
# default.
|
||||
# prefs['python_files'] = ['*.py']
|
||||
|
||||
# Custom source folders: By default rope searches the project
|
||||
# for finding source folders (folders that should be searched
|
||||
# for finding modules). You can add paths to that list. Note
|
||||
# that rope guesses project source folders correctly most of the
|
||||
# time; use this if you have any problems.
|
||||
# The folders should be relative to project root and use '/' for
|
||||
# separating folders regardless of the platform rope is running on.
|
||||
# 'src/my_source_folder' for instance.
|
||||
# prefs.add('source_folders', 'src')
|
||||
|
||||
# You can extend python path for looking up modules
|
||||
# prefs.add('python_path', '~/python/')
|
||||
|
||||
# Should rope save object information or not.
|
||||
prefs['save_objectdb'] = True
|
||||
prefs['compress_objectdb'] = False
|
||||
|
||||
# If `True`, rope analyzes each module when it is being saved.
|
||||
prefs['automatic_soa'] = True
|
||||
# The depth of calls to follow in static object analysis
|
||||
prefs['soa_followed_calls'] = 0
|
||||
|
||||
# If `False` when running modules or unit tests "dynamic object
|
||||
# analysis" is turned off. This makes them much faster.
|
||||
prefs['perform_doa'] = True
|
||||
|
||||
# Rope can check the validity of its object DB when running.
|
||||
prefs['validate_objectdb'] = True
|
||||
|
||||
# How many undos to hold?
|
||||
prefs['max_history_items'] = 32
|
||||
|
||||
# Shows whether to save history across sessions.
|
||||
prefs['save_history'] = True
|
||||
prefs['compress_history'] = False
|
||||
|
||||
# Set the number spaces used for indenting. According to
|
||||
# :PEP:`8`, it is best to use 4 spaces. Since most of rope's
|
||||
# unit-tests use 4 spaces it is more reliable, too.
|
||||
prefs['indent_size'] = 4
|
||||
|
||||
# Builtin and c-extension modules that are allowed to be imported
|
||||
# and inspected by rope.
|
||||
prefs['extension_modules'] = []
|
||||
|
||||
# Add all standard c-extensions to extension_modules list.
|
||||
prefs['import_dynload_stdmods'] = True
|
||||
|
||||
# If `True` modules with syntax errors are considered to be empty.
|
||||
# The default value is `False`; When `False` syntax errors raise
|
||||
# `rope.base.exceptions.ModuleSyntaxError` exception.
|
||||
prefs['ignore_syntax_errors'] = False
|
||||
|
||||
# If `True`, rope ignores unresolvable imports. Otherwise, they
|
||||
# appear in the importing namespace.
|
||||
prefs['ignore_bad_imports'] = False
|
||||
|
||||
# If `True`, rope will insert new module imports as
|
||||
# `from <package> import <module>` by default.
|
||||
prefs['prefer_module_from_imports'] = False
|
||||
|
||||
# If `True`, rope will transform a comma list of imports into
|
||||
# multiple separate import statements when organizing
|
||||
# imports.
|
||||
prefs['split_imports'] = False
|
||||
|
||||
# If `True`, rope will remove all top-level import statements and
|
||||
# reinsert them at the top of the module when making changes.
|
||||
prefs['pull_imports_to_top'] = True
|
||||
|
||||
# If `True`, rope will sort imports alphabetically by module name instead
|
||||
# of alphabetically by import statement, with from imports after normal
|
||||
# imports.
|
||||
prefs['sort_imports_alphabetically'] = False
|
||||
|
||||
# Location of implementation of
|
||||
# rope.base.oi.type_hinting.interfaces.ITypeHintingFactory In general
|
||||
# case, you don't have to change this value, unless you're an rope expert.
|
||||
# Change this value to inject you own implementations of interfaces
|
||||
# listed in module rope.base.oi.type_hinting.providers.interfaces
|
||||
# For example, you can add you own providers for Django Models, or disable
|
||||
# the search type-hinting in a class hierarchy, etc.
|
||||
prefs['type_hinting_factory'] = (
|
||||
'rope.base.oi.type_hinting.factory.default_type_hinting_factory')
|
||||
|
||||
|
||||
def project_opened(project):
|
||||
"""This function is called after opening the project"""
|
||||
# Do whatever you like here!
|
|
@ -1,7 +0,0 @@
|
|||
def inputTypeCheck(message, type, errorMessage):
|
||||
while True:
|
||||
inputValue = input(message)
|
||||
try:
|
||||
return type(inputValue)
|
||||
except ValueError:
|
||||
print(errorMessage)
|
|
@ -1,31 +0,0 @@
|
|||
from common import inputTypeCheck
|
||||
|
||||
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 = inputTypeCheck(
|
||||
message = 'Hvor mange cookies ønsker du å bake? ',
|
||||
type = float,
|
||||
errorMessage = 'Beklager, det du skrev inn er ikke et tall. Prøv igjen\n'
|
||||
)
|
||||
|
||||
print('Antall cookies:', cookieNumber)
|
||||
cookies.getIngredients(cookieNumber)
|
|
@ -1,79 +0,0 @@
|
|||
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))
|
|
@ -1,7 +0,0 @@
|
|||
def inputTypeCheck(message, type, errorMessage):
|
||||
while True:
|
||||
inputValue = input(message)
|
||||
try:
|
||||
return type(inputValue)
|
||||
except ValueError:
|
||||
print(errorMessage)
|
|
@ -1,28 +0,0 @@
|
|||
import math
|
||||
from common import inputTypeCheck
|
||||
|
||||
# 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
|
||||
|
||||
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}')
|
|
@ -1,58 +0,0 @@
|
|||
import math
|
||||
from common import inputTypeCheck
|
||||
|
||||
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)
|
||||
|
||||
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}')
|
|
@ -1,46 +0,0 @@
|
|||
# Known bug:
|
||||
# The program will not accept a name consisting of a single name and a single surname
|
||||
# when the surname only consists of the capital letters IVXLCDM and it will wrongly accept
|
||||
# a surname consisting of those letters as Roman numerals. In order to fix, some more
|
||||
# complex regex logic is needed.
|
||||
|
||||
import re
|
||||
|
||||
capitalize = lambda name: name.capitalize()
|
||||
|
||||
PREPOSITION_LIST = ['von', 'van', 'de', 'di']
|
||||
PREPOSITION_LIST.extend(list(map(capitalize, PREPOSITION_LIST)))
|
||||
SUFFIX_PATTERN = '[sj]r\.?'
|
||||
ROMAN_NUMERAL_PATTERN = '[IVXLCDM]+\.?'
|
||||
|
||||
hasSuffix = lambda word: re.match(SUFFIX_PATTERN, word, re.IGNORECASE) is not None
|
||||
hasRomanNumerals = lambda word: re.match(ROMAN_NUMERAL_PATTERN, word) is not None
|
||||
|
||||
def getName():
|
||||
while True:
|
||||
name = input('Jeg heter: ')
|
||||
if (' ' in name):
|
||||
names = name.split(' ')
|
||||
if not (len(names) == 2 and (hasSuffix(names[-1]) or hasRomanNumerals(names[-1]))):
|
||||
return names
|
||||
print('Putt et mellomrom mellom fornavn og etternavn')
|
||||
|
||||
names = list(map(capitalize, getName()))
|
||||
firstNames = names[:-1]
|
||||
lastNames=[names[-1]]
|
||||
|
||||
moveLastFirstNameToLastNames = lambda: lastNames.insert(0, firstNames.pop())
|
||||
|
||||
|
||||
if hasSuffix or hasRomanNumerals:
|
||||
moveLastFirstNameToLastNames()
|
||||
|
||||
hasPreposition = firstNames[-1] in PREPOSITION_LIST and len(firstNames) != 1
|
||||
|
||||
if hasPreposition:
|
||||
moveLastFirstNameToLastNames()
|
||||
|
||||
lastNamesString = ' '.join(lastNames)
|
||||
firstNamesString = ' '.join(firstNames)
|
||||
|
||||
print(f'The name is {lastNamesString}, {firstNamesString} {lastNamesString}')
|
|
@ -0,0 +1,2 @@
|
|||
main :: IO ()
|
||||
main = putStrLn "Hello world"
|
|
@ -0,0 +1,10 @@
|
|||
main :: IO ()
|
||||
main = do
|
||||
putStrLn $ show $ 1 + 2 * (3+4) + 4/2 - 1
|
||||
|
||||
let minutter = 355 :: Int
|
||||
|
||||
let timer = minutter `div` 60
|
||||
let minutterIgjen = minutter `mod` 60
|
||||
|
||||
putStrLn $ show $ show minutter ++ " minutter blir " ++ show timer ++ " timer og " ++ show minutterIgjen ++ " minutter"
|
|
@ -1,7 +0,0 @@
|
|||
def inputTypeCheck(message, type, errorMessage):
|
||||
while True:
|
||||
inputValue = input(message)
|
||||
try:
|
||||
return type(inputValue)
|
||||
except ValueError:
|
||||
print(errorMessage)
|
|
@ -1,18 +0,0 @@
|
|||
from common import inputTypeCheck
|
||||
|
||||
AVOGADROS_CONSTANT = 6.022e23
|
||||
|
||||
substance = input('Si et stoff du er i besittelse av: ')
|
||||
weight = inputTypeCheck(
|
||||
message='Hva er molvekt i gram for vann? ',
|
||||
type=float,
|
||||
errorMessage='Beklager, det du skrev inn er ikke et tall. Prøv igjen\n'
|
||||
)
|
||||
amount = inputTypeCheck(
|
||||
message='Hvor mange gram vann har du? ',
|
||||
type=float,
|
||||
errorMessage='Beklager, det du skrev inn er ikke et tall. Prøv igjen\n'
|
||||
)
|
||||
|
||||
numberOfMolecules = (amount * AVOGADROS_CONSTANT / weight)
|
||||
print(f'Du har {format(numberOfMolecules, ".1e")} molekyler {substance.lower()}')
|
|
@ -1,13 +0,0 @@
|
|||
from common import inputTypeCheck
|
||||
|
||||
AMOUNT_OF_POSSIBLE_MELODIES = 8.25e19
|
||||
|
||||
melodiesHeard = inputTypeCheck(
|
||||
message = 'Antall ulike 10-toners melodilinjer du har hørt? ',
|
||||
type = int,
|
||||
errorMessage='Beklager, det du skrev inn er ikke et heltall. Prøv igjen\n'
|
||||
)
|
||||
|
||||
percentMelodiesHeard = melodiesHeard / AMOUNT_OF_POSSIBLE_MELODIES * 100
|
||||
|
||||
print(f'Du har hørt {percentMelodiesHeard} prosent av melodier som er mulig.')
|
|
@ -0,0 +1,14 @@
|
|||
main :: IO ()
|
||||
main = do
|
||||
input <- promptLine "Skriv inn h: "
|
||||
let h = read input :: Double
|
||||
putStrLn $ show $ tetraederVolum h
|
||||
|
||||
promptLine :: String -> IO String
|
||||
promptLine prompt = do
|
||||
putStr prompt
|
||||
getLine
|
||||
|
||||
tetraederVolum :: Double -> Double
|
||||
tetraederVolum h = sqrt 2 * a / 12
|
||||
where a = 3 / sqrt 6 * h
|
|
@ -1,4 +0,0 @@
|
|||
# Exercise 1
|
||||
|
||||
## About `common.py`
|
||||
I've copied the function inputTypeCheck() into a common.py for each directory. Normally, I would've made it a module, but to avoid system specific bugs, I've decided not edit global environment variables like PYTHONPATH or edit the sys.path. This means, at least as far as I know, that I can't use relative imports.
|
|
@ -1,7 +0,0 @@
|
|||
def inputTypeCheck(message, type, errorMessage):
|
||||
while True:
|
||||
inputValue = input(message)
|
||||
try:
|
||||
return type(inputValue)
|
||||
except ValueError:
|
||||
print(errorMessage)
|
|
@ -1,25 +0,0 @@
|
|||
from math import sqrt
|
||||
from common import inputTypeCheck
|
||||
|
||||
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(
|
||||
inputTypeCheck(
|
||||
message='Skriv inn en høyde: ',
|
||||
type=float,
|
||||
errorMessage='Beklager, det du skrev inn er ikke et tall. Prøv igjen\n'
|
||||
)
|
||||
)
|
||||
|
||||
print(f'Et tetraeder med høyde {figure2.length} har volum {figure2.getVolume()} og areal {figure2.getArea()}')
|
|
@ -1,18 +0,0 @@
|
|||
print("Dette er et program for å teste din sjenerøsitet.")
|
||||
har_epler = int(input("Hvor mange epler har du? "))
|
||||
if har_epler == 0:
|
||||
print("Æsj, det sier du bare for å slippe å gi noe!")
|
||||
else:
|
||||
gir_epler = int(input("Hvor mange kan du gi til meg? "))
|
||||
if gir_epler < har_epler / 2:
|
||||
print("Du beholder det meste for deg selv...")
|
||||
else:
|
||||
print("Takk, det var snilt!")
|
||||
print("Du har nå", har_epler - gir_epler, "epler igjen.")
|
||||
|
||||
# Logg:
|
||||
# Reindent everything to 2 spaces
|
||||
# line 3: changed = to == for boolean expression
|
||||
# line 5: added a colon after else
|
||||
# line 8: indent print statement
|
||||
# line 9: unindent else
|
|
@ -1,14 +0,0 @@
|
|||
def remainingApplesString(applesLeft):
|
||||
return "Du har nå " + str(applesLeft) + (" epler" if applesLeft != 1 else " eple") +" igjen."
|
||||
|
||||
print("Dette er et program for å teste din sjenerøsitet.")
|
||||
har_epler = int(input("Hvor mange epler har du? "))
|
||||
if har_epler == 0:
|
||||
print("Æsj, det sier du bare for å slippe å gi noe!")
|
||||
else:
|
||||
gir_epler = int(input("Hvor mange kan du gi til meg? "))
|
||||
if gir_epler < har_epler / 2:
|
||||
print("Du beholder det meste for deg selv...")
|
||||
else:
|
||||
print("Takk, det var snilt!")
|
||||
print(remainingApplesString(har_epler - gir_epler))
|
|
@ -1,17 +0,0 @@
|
|||
def remainingApplesString(applesLeft):
|
||||
applesOwed = applesLeft < 0
|
||||
actualApplesLeft = 0 if applesOwed else applesLeft
|
||||
remainingApplesString = "Du har nå " + str(actualApplesLeft) + (" epler" if applesLeft != 1 else " eple") +" igjen."
|
||||
return remainingApplesString + f' Gi meg de {abs(applesLeft)} du skylder meg neste gang vi møtes.' * applesOwed
|
||||
|
||||
print("Dette er et program for å teste din sjenerøsitet.")
|
||||
har_epler = int(input("Hvor mange epler har du? "))
|
||||
if har_epler == 0:
|
||||
print("Æsj, det sier du bare for å slippe å gi noe!")
|
||||
else:
|
||||
gir_epler = int(input("Hvor mange kan du gi til meg? "))
|
||||
if gir_epler < har_epler / 2:
|
||||
print("Du beholder det meste for deg selv...")
|
||||
else:
|
||||
print("Takk, det var snilt!")
|
||||
print(remainingApplesString(har_epler - gir_epler))
|
|
@ -1,23 +0,0 @@
|
|||
def getValues() -> (int, int, int):
|
||||
while True:
|
||||
values = input('Gi inn en andregradsliknings a, b og c separert med mellomrom:\n\t')
|
||||
try:
|
||||
splitValues = values.split(' ')
|
||||
assert len(splitValues) == 3
|
||||
return map(int, splitValues)
|
||||
|
||||
except ValueError:
|
||||
print('Sørg for at alle tallene er heltall.\n')
|
||||
except AssertionError:
|
||||
print('Det skal bare være 3 tall.\n')
|
||||
|
||||
if __name__ == "__main__":
|
||||
a, b, c = getValues()
|
||||
d = b**2 - 4 * a * c
|
||||
|
||||
if d > 0:
|
||||
print('Ligninga har to reelle løsninger')
|
||||
elif d == 0:
|
||||
print('Ligninga har en reell løsning')
|
||||
else:
|
||||
print('Ligninga har to imaginære løsninger')
|
|
@ -1,23 +0,0 @@
|
|||
from math import sqrt
|
||||
|
||||
from task11a import getValues
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
a, b, c = getValues()
|
||||
d = b**2 - 4 * a * c
|
||||
|
||||
expression = f'{a}x^2 + {b}x + {c}'
|
||||
if d > 0:
|
||||
roots = (
|
||||
(-b + sqrt(d)) / (2 * a),
|
||||
(-b - sqrt(d)) / (2 * a)
|
||||
)
|
||||
print(
|
||||
f'Andregradsligningen {expression} har de to reelle løsningene {roots[0]} og {roots[1]}'
|
||||
)
|
||||
elif d == 0:
|
||||
root = (-b + sqrt(d)) / (2 * a)
|
||||
print(f'Andregradsligningen {expression} har en reell dobbelrot {root}')
|
||||
else:
|
||||
print(f'Andregradsligningen {expression} har to imaginære løsninger')
|
|
@ -1,14 +0,0 @@
|
|||
try:
|
||||
from common.inputChecking.typeCheck import inputTypeCheck
|
||||
except ModuleNotFoundError:
|
||||
print('Sjekk README.md for hvilke flagg python trenger')
|
||||
exit(1)
|
||||
|
||||
def evalPrice(daysToTrip):
|
||||
return 'Du kan få minipris: 199,-' if (
|
||||
daysToTrip >= 14) else 'For sent for minipris; fullpris 440,-'
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
daysToTrip = inputTypeCheck('Dager til du skal reise? ', int)
|
||||
print(evalPrice(daysToTrip))
|
|
@ -1,20 +0,0 @@
|
|||
try:
|
||||
from common.inputChecking.boolInput import boolInput
|
||||
from common.inputChecking.typeCheck import inputTypeCheck
|
||||
except ModuleNotFoundError:
|
||||
print('Sjekk README.md for hvilke flagg python trenger')
|
||||
exit(1)
|
||||
|
||||
|
||||
def miniPriceBranch():
|
||||
choseMiniPrice = boolInput('Minipris 199,- kan ikke refunderes/endres\nØnskes dette (J/N)? ')
|
||||
print('Takk for pengene, god reise!' if choseMiniPrice else 'Da tilbyr vi fullpris: 440,-')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
daysToTrip = inputTypeCheck('Dager til du skal reise? ', int)
|
||||
|
||||
if daysToTrip >= 14:
|
||||
miniPriceBranch()
|
||||
else:
|
||||
print('For sent for minipris; fullpris 440,-')
|
|
@ -1,40 +0,0 @@
|
|||
try:
|
||||
from common.inputChecking.boolInput import boolInput
|
||||
from common.inputChecking.typeCheck import inputTypeCheck
|
||||
except ModuleNotFoundError:
|
||||
print('Sjekk README.md for hvilke flagg python trenger')
|
||||
exit(1)
|
||||
|
||||
|
||||
def miniPriceBranch():
|
||||
choseMiniPrice = boolInput(
|
||||
'Minipris 199,- kan ikke refunderes/endres\nØnskes dette (J/N)? ')
|
||||
if choseMiniPrice:
|
||||
print('Takk for pengene, god reise!')
|
||||
else:
|
||||
normalBranch()
|
||||
|
||||
|
||||
def evalDiscountPercent():
|
||||
age = inputTypeCheck('Skriv inn din alder: ', int)
|
||||
if age < 16:
|
||||
return 50
|
||||
elif age >= 60:
|
||||
return 25
|
||||
|
||||
hasSpecialSocialStatus = boolInput('Er du student eller militær (J/N)?')
|
||||
return 25 if hasSpecialSocialStatus else 0
|
||||
|
||||
|
||||
def normalBranch():
|
||||
discountPercent = evalDiscountPercent()
|
||||
print(f'Prisen på biletten blir: {440 - 440 * discountPercent/100}')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
daysToTrip = inputTypeCheck('Dager til du skal reise? ', int)
|
||||
|
||||
if daysToTrip >= 14:
|
||||
miniPriceBranch()
|
||||
else:
|
||||
normalBranch()
|
|
@ -1,34 +0,0 @@
|
|||
try:
|
||||
from common.inputChecking.typeCheck import inputTypeCheck
|
||||
except ModuleNotFoundError:
|
||||
print('Sjekk README.md for hvilke flagg python trenger')
|
||||
exit(1)
|
||||
|
||||
INFO = f"""INFO
|
||||
Dette programmet besvarer om din utleie av egen bolig er skattepliktig.
|
||||
Først trenger vi å vite hvor stor del av boligen du har leid ut.
|
||||
Angi dette i prosent, 100 betyr hele boligen, 50 betyr halve,
|
||||
20 en mindre del av boligen som f.eks. en hybel. """
|
||||
|
||||
HLINE = '----------------------------------------------------------------------'
|
||||
|
||||
def mainBranch():
|
||||
print('DATAINNHENTING:')
|
||||
|
||||
percentRented = inputTypeCheck('Oppgi hvor mye av boligen som ble utleid: ', float)
|
||||
rentIncome = inputTypeCheck('Skriv inn hva du har hatt i leieinntekt: ', float)
|
||||
|
||||
hasTax = percentRented > 50 and rentIncome >= 20000
|
||||
hasTaxString = 'Inntekten er skattepliktig' if hasTax else 'Inntekten er ikke skattepliktig'
|
||||
|
||||
print(HLINE)
|
||||
print('SKATTEBEREGNING')
|
||||
print (hasTaxString)
|
||||
if hasTax:
|
||||
print(f'Skattepliktig beløp er {rentIncome}')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(INFO)
|
||||
print(HLINE)
|
||||
mainBranch()
|
|
@ -1,76 +0,0 @@
|
|||
try:
|
||||
from common.inputChecking.choiceInput import choiceInput
|
||||
from common.inputChecking.typeCheck import inputTypeCheck
|
||||
except ModuleNotFoundError:
|
||||
print('Sjekk README.md for hvilke flagg python trenger')
|
||||
exit(1)
|
||||
|
||||
INFO = """INFO
|
||||
Dette programmet besvarer om din utleie en annen type bolig,
|
||||
her sekundær- eller fritidsbolig, er skattepliktig.
|
||||
Først trenger vi å vite om du leier ut en sekundær- eller en fritidsbolig."""
|
||||
|
||||
HLINE = '---------------------------------------------------------------------'
|
||||
|
||||
FRITIDSBOLIG_INFO = """INFO
|
||||
Du har valgt fritidsbolig.
|
||||
Nå trenger vi først å vite om fritidsboligen(e) primært brukes til utleie eller fritid.
|
||||
Deretter trenger vi å vite hvor mange fritidsbolig(er) du leier ut.
|
||||
Til slutt trenger vi å vite hvor store utleieinntekter du har pr. fritidsbolig."""
|
||||
|
||||
SECONDARYHOUSE_INFO = """INFO
|
||||
Du har valgt sekundærbolig.
|
||||
Nå trenger vi først å vite hvor mange sekundærbolig(er) du leier ut.
|
||||
Deretter trenger vi å vite hvor store utleieinntekter du har pr. sekundærbolig."""
|
||||
|
||||
|
||||
def fritidsboligBranch():
|
||||
print(FRITIDSBOLIG_INFO)
|
||||
print(HLINE)
|
||||
print('DATAINNHENTING:')
|
||||
housePurposeIsRenting = choiceInput(
|
||||
prompt='Skriv inn formålet med fritidsboligen(e): ',
|
||||
choices=['utleie', 'fritid']
|
||||
) == 'utleie'
|
||||
houseAmount = inputTypeCheck('Skriv inn antallet fritidsboliger du leier ut: ', int)
|
||||
rentPerHouse = inputTypeCheck('Skriv inn utleieinntekten pr. fritidsbolig: ', int)
|
||||
print()
|
||||
print(HLINE)
|
||||
print('SKATTEBEREGNING')
|
||||
|
||||
hasTax = housePurposeIsRenting or rentPerHouse > 10000
|
||||
if hasTax:
|
||||
print('Inntekten er skattepliktig')
|
||||
if not housePurposeIsRenting:
|
||||
print(f'Overskytende beløp pr. fritidsbolig er {rentPerHouse - 10000}')
|
||||
|
||||
housePurposeDeduction = 0 if housePurposeIsRenting else 10000
|
||||
taxedRentPerHouse = (rentPerHouse - housePurposeDeduction) * 85/100
|
||||
|
||||
print(f'Skattepliktig inntekt pr. fritidsbolig er {taxedRentPerHouse}')
|
||||
print(f'Totalt skattepliktig beløp er {houseAmount * taxedRentPerHouse}')
|
||||
else:
|
||||
print('Inntekten er ikke skattepliktig')
|
||||
|
||||
def secondaryHouseBranch():
|
||||
print(SECONDARYHOUSE_INFO)
|
||||
print(HLINE)
|
||||
print('DATAINNHENTING:')
|
||||
houseAmount = inputTypeCheck('Skriv inn antallet sekundærboliger du leier ut: ', int)
|
||||
rentPerHouse = inputTypeCheck('Skriv inn utleieinntekten pr. sekundærbolig: ', int)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(INFO)
|
||||
print(HLINE)
|
||||
print('DATAINNHENTING:')
|
||||
houseType = choiceInput(
|
||||
prompt='Skriv inn type annen bolig (sekundærbolig/fritidsbolig) du har leid ut: ',
|
||||
choices=['fritidsbolig','sekundærbolig']
|
||||
)
|
||||
print()
|
||||
|
||||
if houseType == 'fritidsbolig':
|
||||
fritidsboligBranch()
|
||||
else:
|
||||
secondaryHouseBranch()
|
|
@ -1,22 +0,0 @@
|
|||
try:
|
||||
from common.inputChecking.choiceInput import choiceInput
|
||||
except ModuleNotFoundError:
|
||||
print('Sjekk README.md for hvilke flagg python trenger')
|
||||
exit(1)
|
||||
|
||||
from task9a import mainBranch
|
||||
from task9b import fritidsboligBranch, secondaryHouseBranch
|
||||
|
||||
if __name__ == "__main__":
|
||||
choices = ['egen bolig', 'sekundærbolig', 'fritidsbolig']
|
||||
|
||||
choice = choiceInput(
|
||||
prompt=f'Skriv inn hustype for skatteutregning ({", ".join(choices)}): ',
|
||||
choices=choices)
|
||||
|
||||
if choice == 'egen bolig':
|
||||
mainBranch()
|
||||
elif choice == 'sekundærbolig':
|
||||
secondaryHouseBranch()
|
||||
else:
|
||||
fritidsboligBranch()
|
|
@ -1,34 +0,0 @@
|
|||
try:
|
||||
from common.inputChecking.typeCheck import inputTypeCheck
|
||||
except ModuleNotFoundError:
|
||||
print('Sjekk README.md for hvilke flagg python trenger')
|
||||
exit(1)
|
||||
|
||||
def numberPyramid(length):
|
||||
for i in range(length):
|
||||
row = ''
|
||||
for k in range(i + 1):
|
||||
row += f'{k+1} '
|
||||
print(row)
|
||||
|
||||
|
||||
def numberPyramidGenerator():
|
||||
currentList = ['1']
|
||||
while True:
|
||||
yield ' '.join(currentList)
|
||||
currentList.append(str(int(currentList[-1]) + 1))
|
||||
|
||||
|
||||
def solutionWithForLoops(n):
|
||||
return numberPyramid(n)
|
||||
|
||||
|
||||
def solutionWithGenerator(n):
|
||||
myGenerator = numberPyramidGenerator()
|
||||
for i in range(n):
|
||||
print(next(myGenerator))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
n = inputTypeCheck('n: ', int)
|
||||
print(solutionWithForLoops(n))
|
|
@ -1,20 +0,0 @@
|
|||
try:
|
||||
from common.inputChecking.typeCheck import inputTypeCheck
|
||||
except ModuleNotFoundError:
|
||||
print('Sjekk README.md for hvilke flagg python trenger')
|
||||
exit(1)
|
||||
|
||||
def numberPyramid(length):
|
||||
for i in range(length):
|
||||
print('X', ' ' * i + 'X')
|
||||
|
||||
|
||||
def numberPyramidDoubleLoop(length):
|
||||
for i in range(length):
|
||||
space = ''.join([' ' for _ in range(i)])
|
||||
print('X', space + 'X')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
n = inputTypeCheck('n: ', int)
|
||||
numberPyramidDoubleLoop(n)
|
|
@ -1,50 +0,0 @@
|
|||
from math import sqrt
|
||||
|
||||
try:
|
||||
from common.inputChecking.typeCheck import inputTypeCheck
|
||||
except ModuleNotFoundError:
|
||||
print('Sjekk README.md for hvilke flagg python trenger')
|
||||
exit(1)
|
||||
|
||||
# O(√n)
|
||||
def isPrime(n):
|
||||
if n < 2: return False
|
||||
if n == 2 or n == 3 or n == 5: return True
|
||||
limit = int(sqrt(n))
|
||||
numberToCheck = 5
|
||||
while numberToCheck <= limit:
|
||||
if n % numberToCheck == 0: return False
|
||||
numberToCheck += 2 # Skip all even numbers
|
||||
return True
|
||||
|
||||
|
||||
# Would be O(log₂(n)), but isPrime(n) is used,
|
||||
# thus it's O(√n)
|
||||
def findAllFactors(n):
|
||||
factors = []
|
||||
while not isPrime(n):
|
||||
for i in range(2, int(n)):
|
||||
if n % i == 0:
|
||||
factors.append(i)
|
||||
n = n / i
|
||||
break
|
||||
factors.append(int(n))
|
||||
return factors
|
||||
|
||||
|
||||
def factorize(n):
|
||||
factors = []
|
||||
if isPrime(n):
|
||||
factors.append(n)
|
||||
else:
|
||||
factors = findAllFactors(n)
|
||||
return factors
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
n = inputTypeCheck('Skriv inn et positivt heltall: ', int)
|
||||
factors = factorize(n)
|
||||
if len(factors) == 1:
|
||||
print(f'{n} er et primtall')
|
||||
else:
|
||||
print(f'{n} = {" * ".join([str(tall) for tall in factorize(n)])}')
|
|
@ -1,63 +0,0 @@
|
|||
from random import randint
|
||||
|
||||
|
||||
class multiplicationGame:
|
||||
def __init__(self, min, max, tries):
|
||||
self.min = min
|
||||
self.max = max
|
||||
self.tries = tries
|
||||
self.updateProblem()
|
||||
|
||||
def generateNewMultiplicationProblem(self) -> (int, int):
|
||||
number = lambda: randint(self.min, self.max)
|
||||
self.currentProblem = (number(), number())
|
||||
|
||||
def updateProblem(self):
|
||||
self.generateNewMultiplicationProblem()
|
||||
self.currentTries = self.tries
|
||||
|
||||
def userWantsNewQuestion(self) -> bool:
|
||||
while True:
|
||||
answer = input(
|
||||
'Er det ønskelig med flere spørsmål? Skriv 1 for ja og 0 for nei: ')
|
||||
if answer in ['1', '0']:
|
||||
return bool(int(answer))
|
||||
else:
|
||||
print('Skriv 1 for ja og 0 for nei')
|
||||
|
||||
def checkIfUserWantsNewQuestion(self):
|
||||
if not self.userWantsNewQuestion():
|
||||
exit(0)
|
||||
print()
|
||||
|
||||
def wrongAnswer(self):
|
||||
self.currentTries -= 1
|
||||
if self.currentTries == 0:
|
||||
print(
|
||||
'Dessverre klarte du ikke dette regnestykket, men vent så får du et nytt et:)'
|
||||
)
|
||||
self.checkIfUserWantsNewQuestion()
|
||||
self.updateProblem()
|
||||
else:
|
||||
print(f'Dessverre ikke riktig. Du har {self.currentTries} forsøk igjen.')
|
||||
|
||||
def correctAnswer(self):
|
||||
print('Gratulerer, det er helt riktig!')
|
||||
self.checkIfUserWantsNewQuestion()
|
||||
self.updateProblem()
|
||||
|
||||
def update(self):
|
||||
answer = int(input(f'Hva blir {self.currentProblem[0]} * {self.currentProblem[1]}? '))
|
||||
if answer == self.currentProblem[0] * self.currentProblem[1]:
|
||||
self.correctAnswer()
|
||||
else:
|
||||
self.wrongAnswer()
|
||||
|
||||
def loop(self):
|
||||
while True:
|
||||
self.update()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
game = multiplicationGame(min=0, max=10, tries=3)
|
||||
game.loop()
|
|
@ -1,22 +0,0 @@
|
|||
from task11d import multiplicationGame
|
||||
|
||||
class newMultiplicationGame(multiplicationGame):
|
||||
def __init__(self, roundsBetweenDifficultyUpdate, *args, **kwargs):
|
||||
self.roundsBetweenDifficultyUpdate = roundsBetweenDifficultyUpdate
|
||||
self.roundsPlayed = 0
|
||||
return super().__init__(*args, **kwargs)
|
||||
|
||||
def updateDifficulty(self):
|
||||
self.max = self.max + 5
|
||||
print('Oppgavene har nå blitt litt vanskeligere.\n')
|
||||
|
||||
def updateProblem(self):
|
||||
super().updateProblem()
|
||||
self.roundsPlayed += 1
|
||||
if self.roundsPlayed % self.roundsBetweenDifficultyUpdate == 0:
|
||||
self.updateDifficulty()
|
||||
|
||||
if __name__ == "__main__":
|
||||
game = newMultiplicationGame(roundsBetweenDifficultyUpdate=5, min=0, max=10, tries=3)
|
||||
game.loop()
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
try:
|
||||
from common.inputChecking.typeCheck import inputTypeCheck
|
||||
except ModuleNotFoundError:
|
||||
print('Sjekk README.md for hvilke flagg python trenger')
|
||||
exit(1)
|
||||
|
||||
def alternateSum(n):
|
||||
positiveNumbers = [
|
||||
num**2 for num in [i for i in range(1, n + 1) if i % 2 != 0]
|
||||
]
|
||||
negativeNumbers = [
|
||||
-num**2 for num in [i for i in range(1, n + 1) if i % 2 == 0]
|
||||
]
|
||||
return sum(positiveNumbers + negativeNumbers)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
n = inputTypeCheck('n: ', int)
|
||||
print(alternateSum(n))
|
|
@ -1,34 +0,0 @@
|
|||
try:
|
||||
from common.inputChecking.typeCheck import inputTypeCheck
|
||||
except ModuleNotFoundError:
|
||||
print('Sjekk README.md for hvilke flagg python trenger')
|
||||
exit(1)
|
||||
|
||||
def AlternateNumberGenerator():
|
||||
isEven = lambda n: n % 2 == 0
|
||||
n = 1
|
||||
counter = 2
|
||||
while True:
|
||||
yield n
|
||||
n = n + (-counter**2 if isEven(counter) else counter**2)
|
||||
counter += 1
|
||||
|
||||
|
||||
def alternateSumStopAt(k):
|
||||
numGen = AlternateNumberGenerator()
|
||||
previousN = None
|
||||
n = next(numGen)
|
||||
iterations = 0
|
||||
while n < k:
|
||||
previousN = n
|
||||
n = next(numGen)
|
||||
iterations += 1
|
||||
|
||||
print(
|
||||
f'Summen av tallene før summen blir større enn k er {previousN}. Antall iterasjoner: {iterations}'
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
k = inputTypeCheck('k: ', int)
|
||||
alternateSumStopAt(k)
|
|
@ -1,57 +0,0 @@
|
|||
import os
|
||||
|
||||
|
||||
class game():
|
||||
def __init__(self):
|
||||
self.secret_word = input('Skriv inn det hemmelige ordet: ')
|
||||
self.lives = int(input('Hvor mange forsøk får brukeren? '))
|
||||
self.lettersLeft = list(self.secret_word)
|
||||
os.system('clear')
|
||||
|
||||
def getWord(self):
|
||||
return ''.join([('*' if (ch in self.lettersLeft) else ch)
|
||||
for ch in list(self.secret_word)])
|
||||
|
||||
def removeLetterFromLettersLeft(self, letter):
|
||||
self.lettersLeft = list(
|
||||
filter(lambda leftLetter: leftLetter != letter, self.lettersLeft))
|
||||
|
||||
def gameOver(self):
|
||||
print('Du har ingen liv igjen.')
|
||||
exit(0)
|
||||
|
||||
def gameWon(self):
|
||||
print(f'Gratulerer. Ordet var {self.secret_word}')
|
||||
exit(0)
|
||||
|
||||
def wrongLetter(self, letter):
|
||||
print(f'Bokstaven {letter} er ikke i ordet.')
|
||||
self.lives -= 1
|
||||
if self.lives == 0:
|
||||
self.gameOver()
|
||||
print(f'Du har {self.lives} liv igjen, prøv på nytt.')
|
||||
|
||||
def rightLetter(self, letter):
|
||||
print('Stemmer, bokstaven er i ordet')
|
||||
self.removeLetterFromLettersLeft(letter)
|
||||
if self.lettersLeft == []:
|
||||
self.gameWon()
|
||||
|
||||
def update(self):
|
||||
print(self.getWord())
|
||||
letter = input('Gjett på én bokstav i ordet: ')
|
||||
if letter in self.lettersLeft:
|
||||
self.rightLetter(letter)
|
||||
else:
|
||||
self.wrongLetter(letter)
|
||||
|
||||
def loop(self):
|
||||
while True:
|
||||
os.system('clear')
|
||||
self.update()
|
||||
input("Trykk enter for å fortsette...")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
myGame = game()
|
||||
myGame.loop()
|
|
@ -1,25 +0,0 @@
|
|||
try:
|
||||
from common.inputChecking.typeCheck import inputTypeCheck
|
||||
except ModuleNotFoundError:
|
||||
print('Sjekk README.md for hvilke flagg python trenger')
|
||||
exit(1)
|
||||
|
||||
def fibonacciIterative(n):
|
||||
k1 = 0
|
||||
k2 = 1
|
||||
for i in range(n - 1):
|
||||
previousK2 = k2
|
||||
k2 = k1 + k2
|
||||
k1 = previousK2
|
||||
return k1
|
||||
|
||||
|
||||
fibonacciSum = lambda n: sum([fibonacciIterative(i) for i in range(1, n + 1)])
|
||||
fibonacciList = lambda n: [fibonacciIterative(i) for i in range(1, n + 1)]
|
||||
|
||||
if __name__ == "__main__":
|
||||
n = inputTypeCheck('n: ', int)
|
||||
|
||||
print(f'a) Fibonacci({n})', fibonacciIterative(n))
|
||||
print(f'b) Sum av Fibonacci(1..{n})', fibonacciSum(n))
|
||||
print(f'c) Sum av Fibonacci(1..{n})', fibonacciList(n))
|
|
@ -1,21 +0,0 @@
|
|||
month = input('Skriv inn en måned: ').lower()
|
||||
if month == 'februar':
|
||||
year = input('Skriv inn et år: ')
|
||||
isLeapyear = int(year) % 4 == 0
|
||||
print(29 if isLeapyear else 28)
|
||||
else:
|
||||
months = {
|
||||
"januar": 31,
|
||||
# "februar": 30,
|
||||
"mars": 31,
|
||||
"april": 30,
|
||||
"mai": 31,
|
||||
"juni": 30,
|
||||
"july": 31, # Hmmm
|
||||
"august": 31,
|
||||
"september": 30,
|
||||
"oktober": 31,
|
||||
"november": 30,
|
||||
"desember": 31
|
||||
}
|
||||
print(months[month])
|
|
@ -1,32 +0,0 @@
|
|||
months = {
|
||||
"januar": 31,
|
||||
# "februar": 30,
|
||||
"mars": 31,
|
||||
"april": 30,
|
||||
"mai": 31,
|
||||
"juni": 30,
|
||||
"july": 31, # Hmmm
|
||||
"august": 31,
|
||||
"september": 30,
|
||||
"oktober": 31,
|
||||
"november": 30,
|
||||
"desember": 31
|
||||
}
|
||||
|
||||
def myMonth():
|
||||
while True:
|
||||
try:
|
||||
month = input('Skriv inn en måned: ').lower()
|
||||
if month == 'februar':
|
||||
year = int(input('Skriv inn et år: '))
|
||||
assert ((year >= 0) and ( year <= 2020))
|
||||
isLeapyear = year % 4 == 0
|
||||
days = 29 if isLeapyear else 28
|
||||
else:
|
||||
assert month in months
|
||||
days = month[month]
|
||||
return f'Det er {days} dager i denne måneden'
|
||||
except:
|
||||
print('Ugyldig input! Prøv på nytt!')
|
||||
|
||||
print(myMonth)
|
|
@ -1,4 +0,0 @@
|
|||
import re
|
||||
|
||||
def correct_word(string):
|
||||
return bool(re.match('^\w+$', string))
|
|
@ -1,8 +0,0 @@
|
|||
import re
|
||||
|
||||
def count_letters(string):
|
||||
try:
|
||||
assert bool(re.match('^\w+$', string))
|
||||
return len(string)
|
||||
except AssertionError:
|
||||
return -1
|
|
@ -1,5 +0,0 @@
|
|||
def spam_with_questions(question) -> str:
|
||||
while True:
|
||||
answer = input(question).lower()
|
||||
if answer == 'stopp':
|
||||
break
|
|
@ -1,12 +0,0 @@
|
|||
def energy_efficient_spamming(q1, q2):
|
||||
try:
|
||||
assert len(q1)>len(q2)
|
||||
answer = input(q1)
|
||||
while True:
|
||||
if answer == 'stopp':
|
||||
break
|
||||
answer = input(q2)
|
||||
except AssertionError:
|
||||
return
|
||||
|
||||
energy_efficient_spamming('jadu', 'nei')
|
|
@ -1,3 +0,0 @@
|
|||
def triangle(h):
|
||||
for n in range(1,h+1):
|
||||
print('* '*n)
|
|
@ -1,3 +0,0 @@
|
|||
def triangle(h):
|
||||
for n in reversed(range(1,h+1)):
|
||||
print('* '*n)
|
|
@ -1,4 +0,0 @@
|
|||
def isosceles_triangle(h):
|
||||
for i in range(1, h+1):
|
||||
spaces = h-i
|
||||
print(spaces*' ' + i*'* ')
|
|
@ -1,13 +0,0 @@
|
|||
def cubeInput():
|
||||
while True:
|
||||
try:
|
||||
l,w,h = (float(input('Lengde: ')), float(input('Bredde: ')), float(input('Høyde: ')))
|
||||
assert w != l and l != h and w != h
|
||||
return (l,w,h)
|
||||
except AssertionError:
|
||||
print('Morten er ikke fornøyd, prøv igjen')
|
||||
except ValueError:
|
||||
print('Det er ikke et tall, prøv igjen')
|
||||
|
||||
d = min(cubeInput())
|
||||
print(f'Den største kuben vil ha et volum på {d**3}')
|
|
@ -1,4 +0,0 @@
|
|||
x = 3
|
||||
while x:
|
||||
print('#'*x)
|
||||
x-=1
|
|
@ -1 +0,0 @@
|
|||
print(f'Det minste talled du skrev inn var { min([int(input("Skriv et tall: ")) for _ in range(5)]) }.')
|
|
@ -1,3 +0,0 @@
|
|||
def print_table(n):
|
||||
for a in range(1, n+1):
|
||||
print(' '.join([str(a*b) for b in range(1, n+1)]))
|
|
@ -1,208 +0,0 @@
|
|||
# from common.inputChecking.choiceInput import choiceInput
|
||||
|
||||
from os import get_terminal_size, system
|
||||
from math import ceil
|
||||
import random
|
||||
|
||||
class Card:
|
||||
def __init__(self, cardId, color):
|
||||
"""
|
||||
cardId goes from 1 to 1 where 1 is A and 13 is K
|
||||
"""
|
||||
|
||||
self.id = cardId
|
||||
self.color = color
|
||||
|
||||
cardNums = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
|
||||
cardSyms = {
|
||||
'spade': '♠',
|
||||
'heart': '♥',
|
||||
'diamond': '♦',
|
||||
'club': '♣'
|
||||
}
|
||||
|
||||
self.num = cardNums[cardId-1]
|
||||
self.sym = cardSyms[color]
|
||||
|
||||
WIDTH = 11
|
||||
|
||||
def __str__(self):
|
||||
return f"""┌─────────┐
|
||||
│{self.num}{' ' if self.id != 10 else ''} │
|
||||
│ │
|
||||
│ │
|
||||
│ {self.sym} │
|
||||
│ │
|
||||
│ │
|
||||
│ {' ' if self.id != 10 else ''}{self.num}│
|
||||
└─────────┘"""
|
||||
|
||||
def emptyCard():
|
||||
result = Card(1,'spade')
|
||||
result.num = '?'
|
||||
result.sym = '?'
|
||||
return result
|
||||
|
||||
|
||||
class CardHandler:
|
||||
def __init__(self, cards, printSep=5, aceValue = 1):
|
||||
self.cards = cards
|
||||
self.printSeparator = printSep
|
||||
self.aceValue = aceValue
|
||||
|
||||
def addCard(self, card):
|
||||
self.cards.append(card)
|
||||
|
||||
def _concatenateCards(self, cards):
|
||||
"""
|
||||
Concatenate several card objects into an list of sublists
|
||||
where each sublist contains the strings for the cards to be
|
||||
printed for a specific horizontal line.
|
||||
"""
|
||||
|
||||
cardStringLists = [(str(card)).split('\n') for card in cards]
|
||||
cardHeight = len(cardStringLists[0])
|
||||
linesToPrint = [[] for line in range(cardHeight)]
|
||||
|
||||
for cardStringList in cardStringLists:
|
||||
[linesToPrint[line].append(cardStringList[line]) for line in range(cardHeight)]
|
||||
return linesToPrint
|
||||
|
||||
|
||||
def printCards(self, cardsPerLine):
|
||||
"""
|
||||
Print cardsPerLine cards per line, horizontally aligned
|
||||
"""
|
||||
|
||||
splitCards =[[] for _ in range(ceil(len(self.cards)/cardsPerLine))]
|
||||
|
||||
for i, card in enumerate(self.cards):
|
||||
splitCards[i // cardsPerLine].append(card)
|
||||
|
||||
SplitCardStrings = [self._concatenateCards(cardList) for cardList in splitCards]
|
||||
printCardList = lambda cardList: print('\n'.join([ (' ' * self.printSeparator).join(line) for line in cardList ]))
|
||||
[ printCardList(SplitCardString) for SplitCardString in SplitCardStrings ]
|
||||
|
||||
|
||||
def safePrintCards(self):
|
||||
"""
|
||||
Print the amount of cards that there is room for depending on the terminal width
|
||||
"""
|
||||
cardWidth = Card.WIDTH
|
||||
extendedCardWidth = (cardWidth + self.printSeparator)
|
||||
terminalWidth = get_terminal_size().columns
|
||||
|
||||
isRoomForExtraCard = terminalWidth % extendedCardWidth >= cardWidth
|
||||
cardsPerLine = terminalWidth // extendedCardWidth + (1 if isRoomForExtraCard else 0)
|
||||
|
||||
self.printCards(cardsPerLine)
|
||||
|
||||
|
||||
@property
|
||||
def cardSum(self):
|
||||
values = {
|
||||
'A': self.aceValue,
|
||||
'2': 2,
|
||||
'3': 3,
|
||||
'4': 4,
|
||||
'5': 5,
|
||||
'6': 6,
|
||||
'7': 7,
|
||||
'8': 8,
|
||||
'9': 9,
|
||||
'10': 10,
|
||||
'J': 10,
|
||||
'Q': 10,
|
||||
'K': 10
|
||||
}
|
||||
return sum([values[card.num] for card in self.cards])
|
||||
|
||||
def animator(self):
|
||||
while True:
|
||||
frame = 1
|
||||
yield frame
|
||||
|
||||
#
|
||||
# ┌─────────┐
|
||||
# │? │
|
||||
# │ │
|
||||
# │ │
|
||||
# │ ? │
|
||||
# │ │
|
||||
# │ │
|
||||
# │ ?│
|
||||
# └─────────┘
|
||||
#
|
||||
#
|
||||
# ┌────────┐
|
||||
# │? │
|
||||
# │ │
|
||||
# │ │
|
||||
# │ ? │
|
||||
# │ │
|
||||
# │ │
|
||||
# │ ?│
|
||||
# └────────┘
|
||||
#
|
||||
#
|
||||
# ┌───────┐
|
||||
# │? │
|
||||
# │ │
|
||||
# │ │
|
||||
# │ ? │
|
||||
# │ │
|
||||
# │ │
|
||||
# │ ?│
|
||||
# └───────┘
|
||||
#
|
||||
|
||||
|
||||
class Blackjack:
|
||||
def __init__(self):
|
||||
self.handler = CardHandler([])
|
||||
self.emptyHandler = CardHandler([emptyCard(), emptyCard()])
|
||||
self.dealerHandler = CardHandler([])
|
||||
self.reset()
|
||||
|
||||
def generateNewCard(self):
|
||||
cardTypes = range(1,14)
|
||||
cardColors = ['spade', 'heart', 'diamond', 'club']
|
||||
return Card(random.choice(cardTypes), random.choice(cardColors))
|
||||
|
||||
def generateNewCards(self):
|
||||
self.dealerHandler.cards = [ self.generateNewCard() for _ in range(2) ]
|
||||
self.handler.cards = [ self.generateNewCard() for _ in range(2) ]
|
||||
|
||||
def determineAceValue(self):
|
||||
if self.dealerHandler.cardSum <= 9:
|
||||
self.handler.aceValue = 13
|
||||
|
||||
|
||||
def reset(self):
|
||||
self.generateNewCards()
|
||||
self.determineAceValue()
|
||||
|
||||
def printCards(self):
|
||||
self.handler.safePrintCards()
|
||||
|
||||
def update(self):
|
||||
|
||||
system('clear')
|
||||
|
||||
print('\nDEALERS CARDS\n')
|
||||
self.emptyHandler.safePrintCards()
|
||||
print('\nYOUR CARDS\n')
|
||||
self.handler.safePrintCards()
|
||||
print()
|
||||
|
||||
input('Continue?')
|
||||
self.handler.addCard(self.generateNewCard())
|
||||
|
||||
def loop(self):
|
||||
while True:
|
||||
self.update()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
game = Blackjack()
|
||||
game.loop()
|
39
README.md
39
README.md
|
@ -1,39 +0,0 @@
|
|||
# TDT4109 ITGK Øvinger
|
||||
|
||||
Dette er en [git-repo][git-repo] hvor jeg samler opp alle øvingene for TDT4109.
|
||||
|
||||
## Kjøring
|
||||
|
||||
Flere av skriptene deler funksjoner fra mappen `common`. For at disse skal kjøre på en korrekt måte, må de kjøres som moduler og ikke alenestående skript.
|
||||
|
||||
Eksempel på hvordan man skal kjøre en fil:
|
||||
|
||||
```bash
|
||||
python3 -m "Exercise 3.11 - Doble lokker.11a"
|
||||
```
|
||||
|
||||
Eksempel på hvordan man **ikke** skal kjøre filen:
|
||||
|
||||
```bash
|
||||
python3 "Exercise 3/11 - Doble lokker/11a.py"
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
Hver oppgave kommer med eksempel på kjøring, og dette eksempelet i tillegg til andre eksempler blir testet med python sitt innebygde bibliotek som heter `unittest`. Hver øving har en mappe som heter test, hvor alle testene for de forskjellige skriptene ligger, og man kan automatisk teste en av- eller alle filene med kommandoen:
|
||||
|
||||
```bash
|
||||
python -m unittest -s 'Exercise <x>/test'
|
||||
```
|
||||
|
||||
## Komprimering og innlevering
|
||||
|
||||
I hovedmappa ligger det en fil med navn `zipExercise.py`. Denne tar inn ett mappenavn som argument, og sørger for å inkludere alle `common`-modulene som ble brukt, fjerne `__pycache__`, i tillegg til å kopiere denne readme-filen inn i zip-mappa.
|
||||
|
||||
Eksempel på bruk:
|
||||
|
||||
```bash
|
||||
python zipExercise.py "./Exercise 3"
|
||||
```
|
||||
|
||||
[git-repo]: https://gitlab.stud.idi.ntnu.no/oysteikt/tdt4109-itgk/
|
|
@ -1,15 +0,0 @@
|
|||
def removeEmptyDecimals(n):
|
||||
"""
|
||||
Removes .0 from a float if it doesn't add any extra value to the number.
|
||||
|
||||
Parameters:
|
||||
n (float): the value to parse
|
||||
|
||||
```
|
||||
>>> removeEmptyDecimals(2.0)
|
||||
2
|
||||
>>> removeEmptyDecimals(2.5)
|
||||
2.5
|
||||
```
|
||||
"""
|
||||
return int(n) if int(n) == n else n
|
|
@ -1,18 +0,0 @@
|
|||
def boolInput(question, error='Skriv in J eller N\n', yesNoLetters=('j', 'n')):
|
||||
"""
|
||||
Asks the user a yes/no question and returns a bool based on the input.
|
||||
|
||||
Parameters: \\
|
||||
prompt (str): The prompt asking the user for input \\
|
||||
error? (str): The message to be printed on parsing error \\
|
||||
yesNoLetters? ((str,str)): The letters to be used for representing yes and no in lower caps
|
||||
"""
|
||||
yesLetters = [yesNoLetters[0], yesNoLetters[0].capitalize()]
|
||||
noLetters = [yesNoLetters[1], yesNoLetters[1].capitalize()]
|
||||
while True:
|
||||
try:
|
||||
choice = input(question)
|
||||
assert choice in yesLetters + noLetters
|
||||
return choice in yesLetters
|
||||
except AssertionError:
|
||||
print(error)
|
|
@ -1,18 +0,0 @@
|
|||
def choiceInput(prompt, choices):
|
||||
"""
|
||||
Prompts the user to make a choice and asserts that the choice is valid.
|
||||
|
||||
Parameters: \\
|
||||
prompt (str): The prompt asking the user for input \\
|
||||
choices ([str]): The choices that the user can choose (in lower caps)
|
||||
|
||||
Returns the choice in lower caps
|
||||
"""
|
||||
allChoices = choices + [choice.capitalize() for choice in choices]
|
||||
while True:
|
||||
try:
|
||||
answer = input(prompt)
|
||||
assert answer in allChoices
|
||||
return answer.lower()
|
||||
except AssertionError:
|
||||
print('Skriv inn enten', ', '.join(choices[:-1]), 'eller', choices[-1])
|
|
@ -1,19 +0,0 @@
|
|||
def inputTypeCheck(
|
||||
prompt,
|
||||
type,
|
||||
error="Kunne ikke tolke input. Har du skrevet det inn riktig?"
|
||||
):
|
||||
"""
|
||||
Typechecks an input, and only returns the input when it could be successfully parsed.
|
||||
|
||||
Parameters: \\
|
||||
prompt (str): The prompt asking the user for input \\
|
||||
type (fun): The function to be used for parsing \\
|
||||
error? (str): The message to be printed on parsing error
|
||||
"""
|
||||
while True:
|
||||
inputValue = input(prompt)
|
||||
try:
|
||||
return type(inputValue)
|
||||
except ValueError:
|
||||
print(error)
|
|
@ -1,98 +0,0 @@
|
|||
from os import path, mkdir, makedirs, walk
|
||||
from shutil import copytree, copyfile, move, rmtree, make_archive, Error
|
||||
import sys
|
||||
|
||||
|
||||
class zipper:
|
||||
def __init__(self, exerciseDir):
|
||||
self.exerciseDir = exerciseDir
|
||||
self.exerciseName = path.basename(path.abspath(self.exerciseDir))
|
||||
self.zipRootDir = path.join('/tmp/pythonExercises', self.exerciseName)
|
||||
|
||||
|
||||
def __str__(self):
|
||||
return f"""exerciseDir: {self.exerciseDir}
|
||||
zipRootDir: {self.zipRootDir}
|
||||
exerciseName:{self.exerciseName}"""
|
||||
|
||||
|
||||
def copyToTemp(self):
|
||||
makedirs(self.zipRootDir, exist_ok=True)
|
||||
copytree(self.exerciseDir, path.join(self.zipRootDir, self.exerciseName))
|
||||
|
||||
|
||||
def removePycache(self):
|
||||
print('Removing pycaches')
|
||||
|
||||
directories = list()
|
||||
for (dirpath, dirnames, *_) in walk(self.zipRootDir):
|
||||
directories += [path.join(dirpath, directory) for directory in dirnames]
|
||||
|
||||
for directory in directories:
|
||||
if path.basename(directory) == '__pycache__':
|
||||
rmtree(directory)
|
||||
|
||||
|
||||
def importLibs(self):
|
||||
print('Adding files from common')
|
||||
copytree(
|
||||
path.join(self.exerciseDir, '../common'),
|
||||
path.join(self.zipRootDir, 'common')
|
||||
)
|
||||
|
||||
|
||||
def addReadme(self):
|
||||
print('Adding readme')
|
||||
readme = path.join(self.exerciseDir, '../README.md')
|
||||
copyfile(readme, path.join(self.zipRootDir, 'README.md'))
|
||||
|
||||
|
||||
def pauseToMakeChanges(self):
|
||||
input('Make your changes now and then press any key...')
|
||||
|
||||
|
||||
def zipToCWD(self,cwd):
|
||||
print('Moving zipfile back to current directory')
|
||||
archive = make_archive(
|
||||
base_name=path.join(cwd ,self.exerciseName),
|
||||
format='zip',
|
||||
root_dir=path.dirname(self.zipRootDir),
|
||||
base_dir=path.basename(self.zipRootDir)
|
||||
)
|
||||
|
||||
|
||||
# try:
|
||||
# move(archive, cwd)
|
||||
# except Error:
|
||||
# print(f'Error: {path.abspath(cwd)}/{archive} already exists')
|
||||
|
||||
|
||||
def cleanTemp(self):
|
||||
print('Cleaning...')
|
||||
try:
|
||||
rmtree(self.zipRootDir)
|
||||
except FileNotFoundError:
|
||||
print('No existing folder at', self.zipRootDir)
|
||||
|
||||
|
||||
def makeZip(self):
|
||||
print(f'Making zip archive from{self.exerciseDir}\n')
|
||||
|
||||
self.cleanTemp()
|
||||
self.copyToTemp()
|
||||
self.importLibs()
|
||||
self.removePycache()
|
||||
self.addReadme()
|
||||
self.pauseToMakeChanges()
|
||||
self.zipToCWD(path.join(self.exerciseDir, '..'))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
exerciseDir = sys.argv[1]
|
||||
except IndexError:
|
||||
print(f'Example of usage:\n\tpython {path.basename(__file__)} "Exercise 3"')
|
||||
exit(1)
|
||||
|
||||
myZipper = zipper(exerciseDir)
|
||||
myZipper.makeZip()
|
Loading…
Reference in New Issue