Skip to content
Snippets Groups Projects
Commit ff81ad33 authored by Morten Hannemose's avatar Morten Hannemose
Browse files

Update week03

parent bf74f11e
Branches
No related tags found
No related merge requests found
Showing
with 431 additions and 118 deletions
......@@ -9,21 +9,15 @@ cache.db
*.artifacts.pkl
.coveragerc
*_tests_complete_grade.py
tmp.txt
tmp.zip
# Lock file. DISABLE checking with gitlab (and syncing), so you *wnat* this on your computer, but *not* on the students computer.
**/unitgrade_data/dont_check_remote.lock
cp/ex03/simple_function.py
cp/tests/unitgrade_data/Week01Dummy.pkl
cp/tests/unitgrade_data/Week01Palindrome.pkl
######################## Comment these out upon release. #############################
cp/ex03
cp/ex04
cp/ex05
cp/ex06
cp/ex07
cp/ex08
cp/ex09
cp/ex10
cp/ex11
cp/ex12
cp/ex13
cp/exam
#cp/project1
cp/project2
......@@ -32,3 +26,12 @@ cp/project4
cp/project5
cp/project6
cp/tests/tests_week01.py
*04*
*05*
*06*
*07*
*08*
*09*
*10*
*11*
*12*
"""Exercises for week 3."""
"""Exercise 3.10: Ackermann's function."""
def ackermann(m:int, n:int):
"""Compute the Ackermann's function :math:`A(m, n)`.
Your implementation should use recursion and not loops.
:param m: the variable m.
:param n: the variable n.
:return: the computed value :math:`A(m,n)`.
"""
# TODO: Code has been removed from here.
"""Exercise 3.6: BAC Calculator."""
def bac_calculator(alcohol_consumed: float, weight: float, gender: str, time: float) -> float:
"""Calculate the blood alcohol concentration based on the alcohol consumed, body weight, and time since consumption.
:param alcohol_consumed: The total amount of alcohol consumed in grams (float)
:param weight: The person's body weight in kilograms (float)
:param gender: The person's gender, which must be a string of either "male" or "female" (str)
:param time: The time elapsed since alcohol consumption in hours (float)
:return: The calculated blood alcohol concentration (BAC) as a float value.
"""
# TODO: Code has been removed from here.
"""Problems for the Bisection project in week 3."""
import math
def f(x : float) -> float:
r"""Find the roots of this function.
You should implement the function :math:`f(x)` here. It is defined as:
.. math::
f(x) = \sin(3\cos(\frac{1}{2} x^2))
:param x: The value to evaluate the function in :math:`x`
:return: :math:`f(x)`.
"""
Compute f(x) here.
# TODO: Code has been removed from here.
def is_there_a_root(a : float, b : float) -> bool:
"""Return ``True`` if we are guaranteed there is a root of ``f`` in the interval :math:`[a, b]`.
:param a: Lowest x-value to consider
:param b: Highest x-value to consider
:return: ``True`` if we are guaranteed there is a root otherwise ``False``.
"""
# TODO: Code has been removed from here.
def bisect(xmin : float, xmax : float, delta : float) -> float:
"""Find a candidate root within ``xmin`` and ``xmax`` within the given tolerance.
:param xmin: The minimum x-value to consider
:param xmax: The maximum x-value to consider
:param delta: The tolerance.
:return: The first value :math:`x` which is within ``delta`` distance of a root according to the bisection algorithm
"""
# TODO: Code has been removed from here.
"""Exercise 3.4: Body Temperature."""
def body_temperature(temperature):
"""Calculate the body's response based on the given temperature.
:param temperature: The temperature in degrees Celsius.
:return: The body's response as a string.
"""
# TODO: Code has been removed from here.
"""Exercise 3.5: Compare numbers."""
def compare_numbers(first_number:int, second_number:int) -> str:
"""Return a string based on which number has the greatest numerical value.
:param first_number: first number.
:param second_number: second number.
:return: string stating which number is the greatest.
"""
# TODO: Code has been removed from here.
"""Exercise 3.9: Exponential function."""
def exponential(x : float, n : int) -> float:
"""Compute the exponential :math:`x^n` using recursion.
First focus on the case where :math:`n=0`, then :math:`n > 0` and finally :math:`n < 0`.
:param x: the base number :math:`x`.
:param n: the power :math:`n`.
:return: the computed value.
"""
# TODO: Code has been removed from here.
"""Exercise 3.8: Heart attack."""
def heart_attack(age:int, weight:int, smoker:bool) -> str:
"""Return a string indicating the risk of a person for having heart attack.
:param age: The age of the person.
:param weight: The weight of the person in kilograms.
:param smoker: Does the person smoke cigarettes?
:return: A string, either "low" or "high", indicating the risk for having heart attack.
"""
# TODO: Code has been removed from here.
"""Exercise 3.7: Solar panel."""
def solar_panel(move : bool, swap : bool, hot : bool, empty : bool):
"""Print out whether it is a good idea to install solar panels on an object with the given properties.
:param move: does the object move around?
:param swap: does the object allow swapping or recharging battery?
:param hot: is the object hot to the touch when it is running?
:param empty: are there other empty places near the object?
"""
# TODO: Code has been removed from here.
This diff is collapsed.
No preview for this file type
This diff is collapsed.
......@@ -7,83 +7,79 @@ import unittest
from unitgrade import UTestCase, Report
import math
def string_fixer(s):
return s.strip().replace(' ', ' ')
class TestNormalWeight(UTestCase):
@unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
def test_normal_weight_01(self, mock_stdout):
from cp.ex02.normal_weight import normal_weight
def test_normal_weight_01(self):
from cp.ex02.normal_weight import normal_weight
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
normal_weight(1.47)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "Normal weight is between 40 and 54 kg.")
self.assertEqual(string_fixer(out), string_fixer("Normal weight is between 40 and 54 kg."))
@unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
def test_normal_weight_02(self, mock_stdout):
def test_normal_weight_02(self):
from cp.ex02.normal_weight import normal_weight
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
normal_weight(1.96)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "Normal weight is between 72 and 96 kg.")
self.assertEqual(string_fixer(out), string_fixer("Normal weight is between 72 and 96 kg."))
class TestSurvivalTemperature(UTestCase):
@unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
def test_survival_temperature_01(self, mock_stdout):
def test_survival_temperature_01(self):
from cp.ex02.survival_temperature import survival_temperature
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
survival_temperature(186,0.15)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "Survival temperature is -5.0 degrees.")
self.assertEqual(string_fixer(out), string_fixer("Survival temperature is -5.0 degrees."))
@unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
def test_survival_temperature_02(self, mock_stdout):
from cp.ex02.survival_temperature import survival_temperature
def test_survival_temperature_02(self):
from cp.ex02.survival_temperature import survival_temperature
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
survival_temperature(356,0.33)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "Survival temperature is -7.0 degrees.")
self.assertEqual(string_fixer(out), string_fixer("Survival temperature is -7.0 degrees."))
class TestUnitConversion(UTestCase):
@unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
def test_unit_conversion_01(self, mock_stdout):
def test_unit_conversion_01(self):
from cp.ex02.unit_conversion import unit_conversion
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
unit_conversion(4, 3)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "4 ft 3 in is equal to 130 cm.")
self.assertEqual(string_fixer(out), string_fixer("4 ft 3 in is equal to 130 cm."))
@unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
def test_unit_conversion_02(self, mock_stdout):
def test_unit_conversion_02(self):
from cp.ex02.unit_conversion import unit_conversion
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
unit_conversion(7, 2)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "7 ft 2 in is equal to 218 cm.")
self.assertEqual(string_fixer(out), string_fixer("7 ft 2 in is equal to 218 cm."))
class TestHadlock(UTestCase):
@unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
def test_hadlock_01(self, mock_stdout):
def test_hadlock_01(self):
from cp.ex02.hadlock import hadlock
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
hadlock(35, 36, 12)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "The estimated fetal weight is 5820.8 g.")
self.assertEqual(string_fixer(out), string_fixer("The estimated fetal weight is 5820.8 g."))
@unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
def test_hadlock_02(self, mock_stdout):
def test_hadlock_02(self):
from cp.ex02.hadlock import hadlock
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
hadlock(28.6, 29.6, 6.3)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "The estimated fetal weight is 2070.0 g.")
self.assertEqual(string_fixer(out), string_fixer("The estimated fetal weight is 2070.0 g."))
......
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
......@@ -4,97 +4,100 @@ from unitgrade import Report
import cp
from unitgrade import UTestCase
def string_fixer(s):
return s.strip().replace(' ', ' ')
class Week02FullName(UTestCase):
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_full_name(self, mock_stdout):
def test_full_name(self):
from cp.ex02.full_name import full_name
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
full_name('Donald', 'Duck')
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "Donald Duck")
self.assertEqual(string_fixer(out), string_fixer("Donald Duck"))
class Week02NextThousand(UTestCase):
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_next_thousand_01(self, mock_stdout):
def test_next_thousand_01(self):
from cp.ex02.next_thousand import next_thousand
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
next_thousand(123998)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "124000")
self.assertEqual(string_fixer(out), string_fixer("124000"))
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_next_thousand_02(self, mock_stdout):
def test_next_thousand_02(self):
from cp.ex02.next_thousand import next_thousand
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
next_thousand(-123998)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "-123000")
self.assertEqual(string_fixer(out), string_fixer("-123000"))
class Week02NameLength(UTestCase):
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_name_length(self, mock_stdout):
def test_name_length(self):
from cp.ex02.name_length import name_length
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
name_length('Anita')
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "Your name consists of 5 characters.")
self.assertEqual(string_fixer(out), string_fixer("Your name consists of 5 characters."))
class Week02WindChill(UTestCase):
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_wind_chill_01(self, mock_stdout):
def test_wind_chill_01(self):
from cp.ex02.wind_chill import wind_chill
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
wind_chill(8, 12.8)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "Temperature: 8 degrees feels like 6 degrees.")
self.assertEqual(string_fixer(out), string_fixer("Temperature: 8 degrees feels like 6 degrees."))
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_wind_chill_02(self, mock_stdout):
def test_wind_chill_02(self):
from cp.ex02.wind_chill import wind_chill
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
wind_chill(8, 25.8)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "Temperature: 8 degrees feels like 4 degrees.")
self.assertEqual(string_fixer(out), string_fixer("Temperature: 8 degrees feels like 4 degrees."))
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_wind_chill_03(self, mock_stdout):
def test_wind_chill_03(self):
from cp.ex02.wind_chill import wind_chill
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
wind_chill(-2, 12.8)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "Temperature: -2 degrees feels like -6 degrees.")
self.assertEqual(string_fixer(out), string_fixer("Temperature: -2 degrees feels like -6 degrees."))
class Week02NormalWeight(UTestCase):
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_normal_weight(self, mock_stdout):
def test_normal_weight(self):
from cp.ex02.normal_weight import normal_weight
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
normal_weight(1.73)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "Normal weight is between 56 and 74 kg.")
self.assertEqual(string_fixer(out), string_fixer("Normal weight is between 56 and 74 kg."))
class Week02SurvivalTemperature(UTestCase):
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_survival_temperature(self, mock_stdout):
def test_survival_temperature(self):
from cp.ex02.survival_temperature import survival_temperature
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
survival_temperature(200, 0.1)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "Survival temperature is -27.5 degrees.")
self.assertEqual(string_fixer(out), string_fixer("Survival temperature is -27.5 degrees."))
class Week02UnitConversion(UTestCase):
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_unit_conversion(self, mock_stdout):
def test_unit_conversion(self):
from cp.ex02.unit_conversion import unit_conversion
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
unit_conversion(7, 5)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "7 ft 5 in is equal to 226 cm.")
self.assertEqual(string_fixer(out), string_fixer("7 ft 5 in is equal to 226 cm."))
class Week02Hadlock(UTestCase):
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_hadlock(self, mock_stdout):
def test_hadlock(self):
from cp.ex02.hadlock import hadlock
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
hadlock(31.1, 30.2, 8.3)
out = mock_stdout.getvalue()
self.assertEqual(out.strip(), "The estimated fetal weight is 2990.7 g.")
self.assertEqual(string_fixer(out), string_fixer("The estimated fetal weight is 2990.7 g."))
class Week02Tests(Report): #240 total.
title = "Tests for week 02"
......
from unitgrade import UTestCase, Report
import unittest.mock
import io
import cp
import math
class Week03BodyTemperature(UTestCase):
def test_body_Temperature(self):
with self.capture() as c:
from cp.ex03.body_temperature import body_temperature
result = body_temperature(34.5)
self.assertEqual(result, 'Hypothermia')
result = body_temperature(36.9)
self.assertEqual(result, 'Normal')
result = body_temperature(37.2)
self.assertEqual(result, 'Slight fever')
result = body_temperature(38.5)
self.assertEqual(result, 'Fever')
result = body_temperature(40.1)
self.assertEqual(result, 'Hyperthermia')
class Week03CompareNumbers(UTestCase):
def test_compare_numbers(self):
with self.capture() as c:
from cp.ex03.compare_numbers import compare_numbers
result = compare_numbers(5.,3.)
self.assertEqual(result, 'the first number is greater')
result = compare_numbers(2.,7.)
self.assertEqual(result, 'the second number is greater')
result = compare_numbers(4.,4.)
self.assertEqual(result, 'the numbers are equal')
class Week03BACCalculator(UTestCase):
def test_BAC_calculator(self):
with self.capture() as c:
from cp.ex03.bac_calculator import bac_calculator
result = bac_calculator(0.028, 80., "male", 2.)
self.assertEqual(result,0.02147058823529411)
result = bac_calculator(0.021, 70., "female", 2.)
self.assertEqual(result,0.020545454545454547)
class Week03Ackermann(UTestCase):
def test_ackermann(self):
from cp.ex03.ackermann import ackermann
self.assertEqual(ackermann(0, 0), 1)
self.assertEqual(ackermann(0, 1), 2)
self.assertEqual(ackermann(1, 0), 2)
self.assertEqual(ackermann(1, 1), 3)
self.assertEqual(ackermann(1, 2), 4)
self.assertEqual(ackermann(2, 0), 3)
self.assertEqual(ackermann(2, 1), 5)
self.assertEqual(ackermann(2, 2), 7)
self.assertEqual(ackermann(3, 0), 5)
self.assertEqual(ackermann(3, 1), 13)
self.assertEqual(ackermann(3, 2), 29)
class Week03Exponential(UTestCase):
def test_exponential_with_positive_power(self):
from cp.ex03.exponential import exponential
self.assertEqual(exponential(2, 0), 1.0)
self.assertEqual(exponential(2, 1), 2.0)
self.assertEqual(exponential(2, 2), 4.0)
self.assertEqual(exponential(3, 3), 27.0)
self.assertEqual(exponential(5, 4), 625.0)
def test_exponential_with_negative_power(self):
from cp.ex03.exponential import exponential
self.assertEqual(exponential(2, -1), 0.5)
self.assertEqual(exponential(2, -2), 0.25)
self.assertAlmostEqual(exponential(3, -3), 0.037037037037)
self.assertAlmostEqual(exponential(5, -4), 5**(-4) )
def test_exponential_with_zero_power(self):
from cp.ex03.exponential import exponential
self.assertEqual(exponential(2, 0), 1.0)
self.assertEqual(exponential(3, 0), 1.0)
self.assertEqual(exponential(5, 0), 1.0)
class Week03HeartAttack(UTestCase):
def test_heart_attack_low(self):
from cp.ex03.heart_attack import heart_attack
self.assertEqual(heart_attack(25, 55, False), "low")
self.assertEqual(heart_attack(16, 45, False), "low")
self.assertEqual(heart_attack(30, 58, False), "low")
def test_heart_attack_high(self):
from cp.ex03.heart_attack import heart_attack
self.assertEqual(heart_attack(45, 70, True), "high")
self.assertEqual(heart_attack(11, 70, True), "high")
class Week03SolarPanelTests(UTestCase):
def test_maybe(self):
from cp.ex03.solar_panel import solar_panel
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
solar_panel(True, False, False, False)
out = mock_stdout.getvalue()
self.assertEqual(out.strip().lower(), "maybe")
def test_good_luck(self):
from cp.ex03.solar_panel import solar_panel
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
solar_panel(True, False, True, True)
out = mock_stdout.getvalue()
self.assertEqual(out.strip().lower().splitlines(), ["haha", "good luck"])
def test_probably_not1(self):
from cp.ex03.solar_panel import solar_panel
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
solar_panel(True, True, False, False)
out = mock_stdout.getvalue()
self.assertEqual(out.strip().lower(), "probably not")
def test_probably_not2(self):
from cp.ex03.solar_panel import solar_panel
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
solar_panel(False, False, True, True)
out = mock_stdout.getvalue()
self.assertEqual(out.strip().lower(), "probably not")
def test_sure(self):
from cp.ex03.solar_panel import solar_panel
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
solar_panel(False, False, False, False)
out = mock_stdout.getvalue()
self.assertEqual(out.strip().lower(), "sure")
class Week03TheFunctionToBisect(UTestCase):
def test_f(self):
from cp.ex03.bisect import f
self.assertAlmostEqual(f(0), 0.1411200080598672)
self.assertAlmostEqual(f(1), 0.4871688735635369 )
self.assertAlmostEqual(f(2), -0.9484917234010158)
self.assertAlmostEqual(f(math.pi), 0.6145000731172406 )
self.assertAlmostEqual(f(-10), 0.244199939520782)
self.assertAlmostEqual(f(117), -0.9996260520700749)
class Week03IsThereARoot(UTestCase):
def test_root_exists(self):
from cp.ex03.bisect import is_there_a_root
self.assertTrue(is_there_a_root(1, 3)) # root exists between 0 and pi
def test_no_root_exists(self):
from cp.ex03.bisect import is_there_a_root
self.assertFalse(is_there_a_root(3.2, 3.8)) # no root exists between 0 and 2pi
def test_root_not_found(self):
from cp.ex03.bisect import is_there_a_root
self.assertFalse(is_there_a_root(1, 3.5))
class Week03Bisect(UTestCase):
def test_base_case(self):
from cp.ex03.bisect import bisect
self.assertAlmostEqual(bisect(1, 3, 0.1), 1.8125)
self.assertAlmostEqual(bisect(1, 5.5, 0.1), 4.0234375)
def test_tolerances(self):
from cp.ex03.bisect import bisect
self.assertAlmostEqual(bisect(2, 3.5, 10), 2.75)
self.assertAlmostEqual(bisect(2, 3.5, 0.1), 3.03125)
def test_no_solution(self):
from cp.ex03.bisect import bisect
self.assertTrue(math.isnan(bisect(1, 3.5, 1)))
class Week03Tests(Report):
title = "Tests for week 03"
# version = 1.0
# url = "https://gitlab.compute.dtu.dk/cp/02002students/-/blob/master/cp/tests"
pack_imports = [cp]
individual_imports = []
questions = [
(Week03BodyTemperature, 10),
(Week03CompareNumbers, 10),
(Week03BACCalculator, 10),
(Week03Ackermann, 10),
(Week03Exponential, 10),
(Week03HeartAttack, 10),
(Week03SolarPanelTests, 10),
(Week03TheFunctionToBisect, 5),
(Week03IsThereARoot, 15),
(Week03Bisect, 15),
]
if __name__ == '__main__':
from unitgrade import evaluate_report_student
evaluate_report_student(Week03Tests())
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment