Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • master
1 result

Target

Select target project
No results found
Select Git revision
  • master
1 result
Show changes
450 files
+ 68616
6107
Compare changes
  • Side-by-side
  • Inline

Files

+18 −11
Original line number Diff line number Diff line
@@ -9,22 +9,29 @@ 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/ex05
cp/ex06
cp/ex07
cp/ex08
cp/ex09
cp/ex10
cp/ex11
cp/ex12
cp/exam
cp/project1
#cp/project1
#cp/project2
cp/project3
#cp/project3
cp/project4
cp/project5
cp/project6
cp/tests/tests_week01.py
#*04*
#*05*
#*06*
*07*
*08*
*09*
*10*
*11*
*12*

cp/ex01/examples.py

deleted100644 → 0
+0 −30
Original line number Diff line number Diff line
"""A handful of python programming examples."""
# Example 1
print("Hello world")

# Example 2
print("hello")
print("world")

a = 2
b = 3
c = 1
x = 3
y = a*x**2 + b * x + c

# Example 3
def second_poly(x):
    """Compute a first order polynomial.

    :param x: Input value :math:`x`
    :return: :math:`y = 2x + 4`
    """
    return 2 * x + 4

# example 4
def say_hello(name):
    """Print out "Hello {name}.

    :param name: The name to say hello to
    """
    print("Hello " + name)

cp/ex02/fibonacci.py

deleted100644 → 0
+0 −26
Original line number Diff line number Diff line
"""Exercise 2.3: The Fibonacci sequence and recursion."""

def fibonacci_number(k):
    """Compute the :math:`k`'th Fibonacci number :math:`x_k`.

    The function use the recursive relationship :math:`x_{k+1} = x_k + x_{k-1}`, along with the initial conditions
    :math:`x_0 =0, x_1 = 1`, to complete the sequence up to :math:`k`.

    :param k: An integer
    :return:  The corresponding term :math:`x_k` of the Fibonacci sequence as an integer.
    """
    if k == 0:
        # TODO: 1 lines missing.
        raise NotImplementedError("Insert your solution and remove this error.")
    elif k == 1:
        # TODO: 1 lines missing.
        raise NotImplementedError("Insert your solution and remove this error.")
    else:
        # TODO: 1 lines missing.
        raise NotImplementedError("Fix this stuff")

if __name__ == "__main__":
    print("The term x_0 should be 0, you got:", fibonacci_number(0))
    print("The term x_1 should be 1, you got:", fibonacci_number(1))
    print("The term x_2 should be 1, you got:", fibonacci_number(1))
    print("The term x_6 should be 8, you got:", fibonacci_number(6))

cp/ex02/full_name.py

0 → 100644
+9 −0
Original line number Diff line number Diff line
"""Exercise 2.1: Printing full name."""
def full_name(first_name:str, last_name:str):
    """Determine and print the full name given first name and last name.

    :param first_name: your first name.
    :param last_name: your last name.
    """
    # TODO: Code has been removed from here.
    raise NotImplementedError("Insert your solution and remove this error.")

cp/ex02/hadlock.py

0 → 100644
+12 −0
Original line number Diff line number Diff line
"""Exercise: Estimate fetal weight using Hadlock formula."""
import math

def hadlock(head_circ:float,abdominal_circ:float,femur_length:float):
    """Estimate fetal weight using Hadlock formula.

    :param head_circ: head circumference in cm.
    :param abdominal_circ: abdominal circumference in cm.
    :param femur_length: femur length in cm.
    """
    # TODO: Code has been removed from here.
    raise NotImplementedError("Insert your solution and remove this error.")

cp/ex02/name_length.py

0 → 100644
+8 −0
Original line number Diff line number Diff line
"""Exercise 2.3: Printing number of characters in name."""
def name_length(name:str):
    """Calculate and print the number of characters in name.

    :param name: your name.
    """
    # TODO: Code has been removed from here.
    raise NotImplementedError("Insert your solution and remove this error.")
+10 −0
Original line number Diff line number Diff line
"""Exercise 2.2: Round a number to the next nearest thousand."""
import math

def next_thousand(a:int):
    """Round a number to the next nearest thousand and print.

    :param a: the number to be rounded.
    """
    # TODO: Code has been removed from here.
    raise NotImplementedError("Insert your solution and remove this error.")
+10 −0
Original line number Diff line number Diff line
"""Exercise 2.5: Calculate the normal weight range for a given height."""
import math

def normal_weight(height:float):
    """Calculate and print the range of normal weights for a given height.

    :param height: the height.
    """
    # TODO: Code has been removed from here.
    raise NotImplementedError("Insert your solution and remove this error.")
+9 −0
Original line number Diff line number Diff line
"""Exercise 2.6: Calculate the lowest survival temperature."""
def survival_temperature(metabolic_heat:int, thermal_conductance:float):
    """Calculate and print the lowest survival temperature.

    :param metabolic_heat: the metabolic heat production.
    :param thermal_conductance: the thermal conductance.
    """
    # TODO: Code has been removed from here.
    raise NotImplementedError("Insert your solution and remove this error.")

cp/ex02/taylor.py

deleted100644 → 0
+0 −12
Original line number Diff line number Diff line
"""Problem 1.1."""
def evaluate_taylor(x: float) -> float:
    r"""Compute the third order taylor approximation.

    Compute (and return) the Taylor approximation of :math:`\log(x)`. Remember the function must return a ``float``.

    :param x: The input to evaluate.
    :return: The taylor approximation of :math:`\log(x)`, i.e. :math:`y`
    """
    # TODO: 1 lines missing.
    raise NotImplementedError("Define y = (x-1) - 1/2 * ... here.")
    return y

cp/ex02/taylor_variant1.py

deleted100644 → 0
+0 −3
Original line number Diff line number Diff line
"""Problem 1.2. Implement a function that computes (and return) the third order Taylor-approximation here."""
# TODO: Code has been removed from here.
raise NotImplementedError("Insert your solution and remove this error.")

cp/ex02/taylor_variant2.py

deleted100644 → 0
+0 −7
Original line number Diff line number Diff line
"""Problem 1.3. Compute the third order taylor approximation evaluated in x here and store it in a variable y."""

x = 1.5
# Define y = ... here.
# TODO: 1 lines missing.
raise NotImplementedError("Insert your solution and remove this error.")
# print(y) should work.
+11 −0
Original line number Diff line number Diff line
"""Exercise: Convert length in foot and inch to centimeter."""
import math

def unit_conversion(foot:int, inch:int):
    """Convert length in foot and inch to centimeter.

    :param foot: foot portion of the length in imperical unit.
    :param inch: inch portion of the length in imperical unit.
    """
    # TODO: Code has been removed from here.
    raise NotImplementedError("Insert your solution and remove this error.")

cp/ex02/wind_chill.py

0 → 100644
+9 −0
Original line number Diff line number Diff line
"""Exercise 2.4: Wind chill."""
def wind_chill(temperature:int, windspeed:float):
    """Calculate and print the wind chill temperatures.

    :param temperature: the actual temperature.
    :param windspeed: the wind speed.
    """
    # TODO: Code has been removed from here.
    raise NotImplementedError("Insert your solution and remove this error.")
Original line number Diff line number Diff line
"""Exercise 3.9: Ackermann's function."""
"""Exercise 3.10: Ackermann's function."""

def ackermann(m:int, n:int):
    """Compute the Ackermann's function :math:`A(m, n)`.
@@ -9,5 +9,4 @@ def ackermann(m:int, n:int):
    :param n: the variable n.
    :return: the computed value :math:`A(m,n)`.
    """
    # TODO: 5 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    # TODO: Code has been removed from here. 
Original line number Diff line number Diff line
"""Exercise 3.5: BAC Calculator."""

"""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.
@@ -10,6 +9,4 @@ def bac_calculator(alcohol_consumed: float, weight: float, gender: str, time: fl
    :param time: The time elapsed since alcohol consumption in hours (float)
    :return: The calculated blood alcohol concentration (BAC) as a float value.
    """
    # TODO: 10 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return bac
    # TODO: Code has been removed from here. 
Original line number Diff line number Diff line
@@ -4,19 +4,12 @@ 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:
    You should implement the function f(x) here.

    .. 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)`.
    :param x: The value to evaluate the function in x
    :return: f(x)
    """
    # TODO: 1 lines missing.
    raise NotImplementedError("Compute f(x) here.")
    return y
    # TODO: Code has been removed from here. 


def is_there_a_root(a : float, b : float) -> bool:
@@ -26,9 +19,7 @@ def is_there_a_root(a : float, b : float) -> bool:
    :param b: Highest x-value to consider
    :return: ``True`` if we are guaranteed there is a root otherwise ``False``.
    """
    # TODO: 1 lines missing.
    raise NotImplementedError("Compute the condition here")
    return has_root
    # 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.
@@ -38,19 +29,5 @@ def bisect(xmin : float, xmax : float, delta : float) -> float:
    :param delta: The tolerance.
    :return: The first value :math:`x` which is within ``delta`` distance of a root according to the bisection algorithm
    """
    # TODO: 6 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")



if __name__ == "__main__":
    print("Are we guaranteed there is a zero within the interval [1, 3]?", is_there_a_root(1, 3), "(this should be True)")
    print("Are we guaranteed there is a zero within the interval [1, 3.5]?", is_there_a_root(1, 3.5), "(this should be False)")

    print("Find a zero within tolerance 0.1 in the interval [1, 2]")
    print(bisect(1, 2, 0.1))
    print("Same, but with a tolerance of 0.5")
    print(bisect(1, 2, 0.1))
    # TODO: Code has been removed from here. 
    print("Should return math.nan")
    print(bisect(1, 3.5, 0.1))
Original line number Diff line number Diff line
"""Exercise 3.4: Body Temperature."""

def body_temperature(temperature : float) -> str:
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: 10 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return response
    # TODO: Code has been removed from here. 
Original line number Diff line number Diff line
"""Exercise 3.3: Compare numbers."""
"""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.
@@ -7,6 +7,4 @@ def compare_numbers(first_number:int, second_number:int) -> str:
    :param second_number: second number.
    :return: string stating which number is the greatest.
    """
    # TODO: 6 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return comparison
    # TODO: Code has been removed from here. 
Original line number Diff line number Diff line
"""Exercise 3.8: Exponential function."""
"""Exercise 3.9: Exponential function."""

def exponential(x : float, n : int) -> float:
    """Compute the exponential :math:`x^n` using recursion.
@@ -9,5 +9,4 @@ def exponential(x : float, n : int) -> float:
    :param n: the power :math:`n`.
    :return: the computed value.
    """
    # TODO: 6 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    # TODO: Code has been removed from here. 
Original line number Diff line number Diff line
"""Exercise 3.7: Heart attack."""
"""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.
@@ -8,6 +8,4 @@ def heart_attack(age:int, weight:int, smoker:bool) -> str:
    :param smoker: Does the person smoke cigarettes?
    :return: A string, either "low" or "high", indicating the risk for having heart attack.
    """
    # TODO: 12 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return risk
    # TODO: Code has been removed from here. 

cp/ex03/simple_function.py

deleted100644 → 0
+0 −6
Original line number Diff line number Diff line
"""This example is used in the lecture notes to illustrate the import statement. Ignore it for the exercises."""

def just_a_function(): 
    """Print two lines to the terminal."""
    print("Hello!") 
    print("I am justin-a-function :-).") 
Original line number Diff line number Diff line
"""Exercise 3.6: Solar panel."""
"""Exercise 3.7: Solar panel."""

def solar_panel(move : bool, swap : bool, hot : bool, empty : bool):
def solar_panel(move : bool, swap : bool, hot : bool, empty : bool) -> str:
    """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?
    :return: Whether you should put solar panels on the object as a string.
    """
    # TODO: 19 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    # TODO: Code has been removed from here. 
+4 −5
Original line number Diff line number Diff line
"""Exercise 4.2-4.3: Let the world know you have written your last bug."""
"""Exercise 4.4-4.5: Let the world know you have written your last bug."""

def last_bug():
    """Write a nice message enclosed by lines and pipes that clearly indicate you have written your last bug.
@@ -11,8 +11,7 @@ def last_bug():
        | I have written my last bug |
        ------------------------------
    """
    # TODO: 5 lines missing.
    raise NotImplementedError("Use print(...) to print the output here.")
    # TODO: Code has been removed from here. 


def nice_sign(msg : str):
@@ -29,10 +28,10 @@ def nice_sign(msg : str):
    :param msg: The message to enclose.
    """
    # You can use len(msg) to get the number of characters and "-"*10 to repeat a character (try in the console!)
    # TODO: 4 lines missing.
    raise NotImplementedError("Use print(...) to print the output here.")
    # TODO: Code has been removed from here. 


if __name__ == "__main__":
    # here you can try out your functions
    last_bug()  # Done with the bugs
    nice_sign("Hello world")
+17 −25
Original line number Diff line number Diff line
"""Exercise 4.12-4.16."""

def is_word_guessed(secret_word : str, letters_guessed : str) -> bool:
    """Determine if the word has been guessed.

@@ -6,25 +7,7 @@ def is_word_guessed(secret_word : str, letters_guessed : str) -> bool:
    :param letters_guessed: A ``str`` containing the letters that have currently been guessed
    :return: True if and only if all letters in ``secret_word`` have been guessed.
    """
    # TODO: 4 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return guessed


def get_guessed_word(secret_word : str, letters_guessed : str) -> str:
    """Format the secret word for the user by removing letters that have not been guessed yet.

    Given a list of the available letters, the function will replace the letters in the secret word with `'_ '`
    (i.e., a lower-case followed by a space). For instance, if the secret word is ``"cat"``, and the
    available letters are ``"ct"``, then the function should return ``"c_ t"``.

    :param secret_word: A ``str``, the word the user is guessing
    :param letters_guessed:  A ``str`` containing which letters have been guessed so far
    :return: A ``str``, comprised of letters, underscores (_), and spaces that represents which letters in secret_word have been guessed so far.
    """
    # TODO: 6 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return word
    # TODO: Code has been removed from here. 


def get_available_letters(letters_guessed : str) -> str:
@@ -38,13 +21,22 @@ def get_available_letters(letters_guessed : str) -> str:
    :param letters_guessed: A `str` representing the letters the user has already guessed
    :return: A `str` containing the letters the user has not guessed at yet.
    """
    # TODO: 2 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return letters
    # TODO: Code has been removed from here. 

def get_guessed_word(secret_word : str, letters_guessed : str) -> str:
    """Format the secret word for the user by removing letters that have not been guessed yet.

    Given a list of the available letters, the function will replace the letters in the secret word with `'_ '`
    (i.e., a lower-case followed by a space). For instance, if the secret word is ``"cat"``, and the
    available letters are ``"ct"``, then the function should return ``"c_ t"``.

    :param secret_word: A ``str``, the word the user is guessing
    :param letters_guessed:  A ``str`` containing which letters have been guessed so far
    :return: A ``str``, comprised of letters, underscores (_), and spaces that represents which letters in secret_word have been guessed so far.
    """
    # TODO: Code has been removed from here. 

def hangman(secret_word : str, guesses : str):
def hangman(secret_word : str, guesses : int):
    """
    Play an interactive game of Hangman.

@@ -62,11 +54,11 @@ def hangman(secret_word : str, guesses : str):
    :param guesses: The number of available guesses, for instance ``6``
    """
    # TODO: Code has been removed from here. 
    raise NotImplementedError("Insert your solution and remove this error.")



if __name__ == "__main__":
    # here you can try out your functions
    print("This should return True: ", is_word_guessed("dog", "tdohg"))
    print("This should return False: ", is_word_guessed("dog", "dthk"))

Original line number Diff line number Diff line
@@ -7,19 +7,16 @@ def square_root(a : float) -> float:
    :param a: A number to compute the square root of.
    :return: :math:`\sqrt{a}`.
    """
    # TODO: 7 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return sqrt_a
    # TODO: Code has been removed from here. 

def ramanujan() -> float:
    r"""Compute the Ramanujan approximation of :math:`\pi` using a sufficient number of terms.

    :return: A high-quality approximation of :math:`\pi` as a ``float``.
    """
    # TODO: 9 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return pi
    # TODO: Code has been removed from here. 

if __name__ == "__main__":
    # here you can try out your functions
    print("approximate pi", ramanujan())
    print("square root of 2 is", square_root(2))
Original line number Diff line number Diff line
"""Exercise 4.1: Checking if a word is a palindrome."""
"""Exercise 4.3: Checking if a word is a palindrome."""

def is_palindrome(word : str) -> bool:
    """Check if ``word`` is a palindrome.
@@ -6,10 +6,9 @@ def is_palindrome(word : str) -> bool:
    :param word: The word to check
    :return: ``True`` if input is a palindrome and otherwise ``False``
    """
    # TODO: 2 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return is_a_palindrome
    # TODO: Code has been removed from here. 

if __name__ == "__main__":
    # here you can try out your functions
    print("Is Madam a palindrome?", is_palindrome('madam'))
    print("Is gentleman a palindrome?", is_palindrome('gentleman'))
Original line number Diff line number Diff line
"""Exercise 4.x-4.y."""
"""Exercise 4.6-4.9."""
def matching(expression :str) -> bool:
    """Tell if the parenthesis match in a mathematical expression.

@@ -7,9 +7,19 @@ def matching(expression :str) -> bool:
    :param expression: An expression containing zero or more parenthesis.
    :return: ``True`` if the number of open/close parenthesis match, otherwise ``False``
    """
    # TODO: 9 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return matching
    # TODO: Code has been removed from here. 

def find_innermost_part(s : str) -> str:
    """Find the innermost part of a mathematical expression.

    The innermost part is a substring enclosed in parenthessis but not containing parenthesis.
    For instance, given ``"3(x+(4-y^2))"``, then ``"4-y^2"`` is an inner-most part.
    The parenthesis can be assumed to match.

    :param s: The mathematical expression as a ``str``
    :return: The innermost part as a ``str``
    """
    # TODO: Code has been removed from here. 


def find_index_of_equality(expression : str) -> int:
@@ -23,15 +33,13 @@ def find_index_of_equality(expression : str) -> int:
    - ``"(()"``
    - ``"())"``

    In this case the left-hand part contains ``2`` opening parenthesis and ``2`` closign parenthesis so ``i`` is the right index.
    In this case the left-hand part contains ``2`` opening parenthesis and the right-hand part ``2`` closing parenthesis so ``i`` is the right index.
    Similarly, for ``"()"``, the answer would be ``1``.

    :param expression: An expression only consisting of opening and closing parenthesis.
    :return: The index ``i`` as an int.
    """
    # TODO: 6 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return i
    # TODO: Code has been removed from here. 


def print_the_dialogue(s : str):
@@ -43,26 +51,12 @@ def print_the_dialogue(s : str):

    :param s: The manuscript as a ``str``.
    """
    # TODO: 4 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")

def find_innermost_part(s : str) -> str:
    """Find the innermost part of a mathematical expression.

    The innermost part is a substring enclosed in parenthessis but not containing parenthesis.
    For instance, given ``"3(x+(4-y^2))"``, then ``"4-y^2"`` is an inner-most part.
    The parenthesis can be assumed to match.

    :param s: The mathematical expression as a ``str``
    :return: The innermost part as a ``str``
    """
    # TODO: 3 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return inner_part
    # TODO: Code has been removed from here. 



if __name__ == "__main__":
    # here you can try out your functions
    print("Does the parenthesis match?", matching("2x(x+2)"))
    print("Does the parenthesis match?", matching("2x(x+(2-y)^2)"))
    print("Does the parenthesis match?", matching("4x"))

cp/ex04/play_hangman.py

deleted100644 → 0
+0 −25
Original line number Diff line number Diff line
"""Play a game of hangman by loading a random word."""
import random
import os

def load_words() -> list:
    """
    Return a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.

    :return: The available words as a list.
    """
    from cp.ex08.words import load_words
    wordlist = load_words(os.path.join(os.path.dirname(__file__), "files", "5000-words.txt")).split()
    return wordlist


def choose_word() -> str:
    """Select a word at random.

    :return: A randomly selected word, useful for playing hangman.
    """
    wordlist = load_words()
    return random.choice(wordlist)
Original line number Diff line number Diff line
"""Exercise XX."""

"""Exercise 4.10-4.11."""

def common_prefix(word1 : str, word2 : str) -> str:
    """
@@ -9,9 +8,7 @@ def common_prefix(word1 : str, word2 : str) -> str:
    :param word2: Second word
    :return: The longest common prefix.
    """
    # TODO: 6 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return prefix
    # TODO: Code has been removed from here. 

def common_prefix3(word1 : str, word2 : str, word3 : str) -> str:
    """
@@ -22,12 +19,10 @@ def common_prefix3(word1 : str, word2 : str, word3 : str) -> str:
    :param word3: Third word
    :return: The longest common prefix.
    """
    # TODO: 1 lines missing.
    raise NotImplementedError("Insert your solution and remove this error.")
    return prefix
    # TODO: Code has been removed from here. 


# Driver Code
if __name__ == "__main__":
    # here you can try out your functions
    print("The longest Common Prefix is :", common_prefix("egregious", "egg"))
    print("The longest Common Prefix is :", common_prefix3("egg", "egregious", "eggplant"))

cp/ex05/average.py

0 → 100644
+9 −0
Original line number Diff line number Diff line
"""Exercise 5.2. Average of lists."""

def calculate_average(nums: list) -> float:
    """Return the average of a list of numbers.
    
    :param nums: list of numbers
    :return: average of list
    """
    # TODO: Code has been removed from here. 

cp/ex05/best_buy.py

0 → 100644
+12 −0
Original line number Diff line number Diff line
"""Exercise 5.11. Best Buy."""

def best_buy(prices: list, money: int, start_index: int, reverse: bool) -> int:
    """Return the number of items that can be bought with the given amount of money. The function should be able to handle arbitrary starting points and to run the list in reverse.
    
    :param prices: list of prices
    :param money: amount of money
    :param start_index: starting index in list
    :param reverse: boolean to indicate if list should be run in reverse
    :return: number of items that can be bought with the given amount of money
    """
    # TODO: Code has been removed from here. 
+21 −0
Original line number Diff line number Diff line
"""Exercise 5.3-5.4. Conditioned maximum."""

def conditioned_maximum(nums: list, threshold: float) -> float:
    """Return the maximum of a list of numbers, that is strictly smaller than the given threshold.
    
    :param nums: list of numbers
    :param threshold: limit for maximum value   
    :return: maximum of list thats smaller than the threshold
    """
    # TODO: Code has been removed from here. 


def conditioned_maximum_name(nums: list, names: list, threshold: float) -> str:
    """Return the name of the maximum of a list of numbers, that is smaller than the given threshold.
    
    :param nums: list of numbers with animal heights.
    :param names: list of animal names
    :param threshold: limit for maximum value   
    :return: animal name with the corresponding maximum height, which is shorter than the threshold height.
    """
    # TODO: Code has been removed from here. 

cp/ex05/multiples.py

0 → 100644
+19 −0
Original line number Diff line number Diff line
"""Exercise 5.8.-5-9. Count multiples."""

def count_multiples(numbers: list, m: int)  -> int:
    """Count the number of numbers that are divisible by m.
    
    :param numbers: list of numbers
    :param m: number to divide by
    :return: number of numbers that are divisible by m
    """
    # TODO: Code has been removed from here. 

def multiples_list(numbers: list, m: int)  -> list:
    """Make a list with all numbers from a list that are divisible by m.
    
    :param numbers: list of numbers
    :param m: number to divide by
    :return: list of numbers that are divisible by m
    """
    # TODO: Code has been removed from here. 

cp/ex05/rectangular.py

0 → 100644
+9 −0
Original line number Diff line number Diff line
"""Exercise 5.6. Rectangular list."""

def is_rectangular(nested_list: list) -> bool:
    """Check if a list is rectangular.
    
    :param nested_list: nested list
    :return: True if list is rectangular, False otherwise
    """
    # TODO: Code has been removed from here. 

cp/ex05/short_words.py

0 → 100644
+10 −0
Original line number Diff line number Diff line
"""Exercise 5.5. short words."""

def short_words(words: str, max_len: int) -> str:
    """Return a string of words that are shorter than max_len.
    
    :param words: string of words
    :param max_len: maximum length of words 
    :return: string of words that are shorter than max_len
    """
    # TODO: Code has been removed from here. 

cp/ex05/tictactoe.py

0 → 100644
+35 −0
Original line number Diff line number Diff line
"""Exercise 5.12-5-16. TicTacToe."""
def get_game_state(board: list) -> str:
    """Check if a player has won the game, if it's a draw, or if it's ongoing.

    :param board: List of lists of strings representing the game board.
    :return: A string which is 'X' if player 'X' won, 'O' if player 'O' has won, 'Draw' if the game is a draw, or '-' if the game is ongoing.
    """
    # TODO: Code has been removed from here. 

def update_board(board : list, player: str, position: list) -> list:
    """Update the game board with the player's move.

    :param board: List of lists of strings representing the game board.
    :param player: Player making the move ('X' or 'O').
    :param position: List containing two integer indices [row, column] indicating the position to make a move.
    :return: Updated game board after the move.
    """        
    # TODO: Code has been removed from here. 

def print_board(board: list):
    """Print the current state of the game board.
    
    :param board: List of lists of strings representing the game board.
    """
    # TODO: Code has been removed from here. 

def tictactoe(board: list, player: str, position: list) -> list:
    """Play a move in the Tic-Tac-Toe game and determine the winner.
    
    :param board: List of lists of strings representing the game board.
    :param player: Player making the move ('X' or 'O').
    :param position: List containing two integer indices [row, column] indicating the position to make a move.
    :return: Updated game board after the move.
    """
    # TODO: Code has been removed from here. 

cp/ex05/vector_add.py

0 → 100644
+10 −0
Original line number Diff line number Diff line
"""Exercise 5.7. Vector additon."""

def vector_add(v: list, w: list) -> list:
    """Add two vectors.
    
    :param v: vector 1 (list of numbers)
    :param w: vector 2 (list of numbers, same length as v)
    :return: sum of v and w (list of number)
    """
    # TODO: Code has been removed from here. 
+10 −0
Original line number Diff line number Diff line
"""Exercise 5.10. Water height."""

def water_height(h0: int, r: list) -> int:
    """Calculate the water height after multiple days of rain.

    :param: h0: initial height of the water
    :param: r: list of rain showers
    :return: height of water after days of rain 
    """
    # TODO: Code has been removed from here. 

cp/ex06/__init__.py

0 → 100644
+1 −0
Original line number Diff line number Diff line
"""DO NOT EDIT/ADD TO THIS FILE.""" 

cp/ex06/language.py

0 → 100644
+19 −0
Original line number Diff line number Diff line
"""Exercise 6.5: Languages."""

def get_people_by_language(language: str, name_languages: dict)-> list:
    """Return the names of people who speak a specific language.
    
    :param language: A string containing the desired language.
    :param name_languages: A dictionary containing the names of people along with their spoken languages
    :return: The names of people that speak the desired language.
    """
    # TODO: Code has been removed from here. 
if __name__ == "__main__":
    name_languages = {
    'Peter': ['Danish', 'English'],
    'Alice': ['English', 'French'],
    'John': ['Spanish', 'English'],
    'Maria': ['Danish', 'Spanish'],
    'Anna': ['German', 'English']
    }
    print(get_people_by_language('English', name_languages))

cp/ex06/letter.py

0 → 100644
+14 −0
Original line number Diff line number Diff line
"""Exercise 6.2: Letter histogram."""

def letter_histogram(input_string : str) -> dict:
    """Return the histogram of letter occurrences.
    
    :param input_string: The word based on which the letter histogram is calculated.
    :return: The alphabet characters as keys with their corresponding occurrences as values.
    """
    # TODO: Code has been removed from here. 


if __name__ == "__main__":
    # here you can try out your functions
    print("What is the letter histogram of the word banana?",  letter_histogram('banana'))

cp/ex06/multi_tap.py

0 → 100644
+18 −0
Original line number Diff line number Diff line
"""Exercise 6.9: Multi-tap."""

def multi_tap(keys : list, times : list) -> str:
    """Return the string corresponding to the multi-tap key presses.

    :param keys: The list of keys pressed.
    :param times: The list of times of when the keys were pressed.
    :return: The string corresponding to the key presses.
    """
    # TODO: Code has been removed from here. 
    



if __name__ == "__main__":
    keys = [7, 7, 7, 7, 6, 6, 6]
    times = [0, 0.7, 0.8, 0.9, 1, 1.1, 1.2]
    print(multi_tap(keys, times), '==', 'PRO')

cp/ex06/nato.py

0 → 100644
+13 −0
Original line number Diff line number Diff line
"""Exercise 6.1: The NATO alphabet."""

def text_to_nato(plaintext : str) -> str:
    """Return the NATO version of a word separated by dashes.

    :param plaintext: The word to replace with its phrase according to the NATO alphabet.
    :return: The NATO representation of the input word.
    """
    # TODO: Code has been removed from here. 

if __name__ == "__main__":
    # here you can try out your functions
    print("What is the NATO representation of hello?", text_to_nato('hello'))
+14 −0
Original line number Diff line number Diff line
"""Exercise 6.7: Sentiment analysis."""

def sentiment_analysis(text: str) -> int:
    """Return the sentence sentiment score, according to the rules of words scoring, as described in the text above.

    :param text: The sentence to check for sentiment scoring.
    :return: The total sentiment scoring of the sentence.
    """
    # TODO: Code has been removed from here. 

if __name__ == "__main__":
    # here you can try out your functions
    text='I think the food was excellent and great, but the service was horrible '
    sentiment_analysis(text)

cp/ex06/spell_check.py

0 → 100644
+23 −0
Original line number Diff line number Diff line
"""Exercise 6.8: Spell check."""

def spell_check(text: str, corrections: dict) -> str:
    """Return the corrected text for spelling errors according to a set of rules.

    :param text: The sentence to check for spelling.
    :param corrections: The dictionary of wrongly spelled words and their equivalent corrected version.
    :return: The correctly spelled sentence.
    """
    # TODO: Code has been removed from here. 

if __name__ == "__main__":
    # here you can try out your functions
    corrections = {
    'apsolute': 'absolute',
    'teh': 'the',
    'acess': 'access', 
    'occured': 'occurred',
    'exampel': 'example'
    }
    text = "The apsolute acsess to teh data occured in this exampel."

    print(spell_check(text, corrections))

cp/ex06/truncate.py

0 → 100644
+17 −0
Original line number Diff line number Diff line
"""Exercise 6.6: Truncate and normalize."""

def truncate_values(float_list : list, settings: dict) -> list: 
    """Return a truncated list of floats given the initial list and the settings for truncating. If normalize is True, the values are first normalized to the [0,1] range and then truncated.
    
    :param float_list: list of floats
    :param settings: Dictionary containing the keys vmin, vmax and normalize with their corresponding values.
    :return: Truncated/Normalized+Truncated values.
    """
    # TODO: Code has been removed from here. 

if __name__ == "__main__":
    # here you can try out your functions
    settings = {'vmin': 0, 'vmax': 2, 'normalize': False}
    float_list = [0.5,0.4,-0.3, 1.5, 2.5, 3.5]
    result=truncate_values(float_list=float_list,settings=settings)
    print(result)
+34 −0
Original line number Diff line number Diff line
"""Exercise 6.3-6.4."""

def word_histogram(lines : list) -> dict:
    """Return the word count histogram from the input lines.

    :param lines: The lines that are analyzed for word count.
    :return: The histogram of word occurrences.
    """
    # TODO: Code has been removed from here. 
    
def extract_keyword(lines : str, ignore_list : list) -> dict:
    """Return the five most frequent words that are not on the ignore list and their occurrences.

    :param lines: The sentence to extract keywords from.
    :param ignore_list: The words that should ignored.
    :return: The five most frequent words in the sentence as keys with their count as values.
    """
    # TODO: Code has been removed from here. 


if __name__ == "__main__":
    # here you can try out your functions
    lines = ['This is the first sentence of text for you', 'This is the second sentence of text', 'This is for you']
    print("word_histogram")
    print(word_histogram(lines))

    # Ignore list of common words
    ignore_list = ['the', 'be', 'to', 'of', 'and', 'a', 'in', 'is', 'have', 'I']

    # Print the 5 most occurring keywords
    print("extract_keywords")
    print(extract_keyword(lines, ignore_list))

    

cp/ex07/__init__.py

0 → 100644
+1 −0
Original line number Diff line number Diff line
"""DO NOT EDIT/ADD TO THIS FILE.""" 
+9 −0
Original line number Diff line number Diff line
"""Exercise 7.9: Astronomical season."""

def astronomical_season(date :  tuple) -> str:
    """Return the astronomical season of the given date.

    :param date: Tuple with the given date.
    :return: String with astronomical season
    """
    # TODO: Code has been removed from here. 

cp/ex07/box_packing.py

0 → 100644
+10 −0
Original line number Diff line number Diff line
"""Exercise 7.5: Box packing."""

def box_packing(object : tuple, box : tuple)-> tuple:
    """Return the amount of object sticking in each dimension, or zero if sufficient space.
    
    :param object: Tuple (h,w) the dimensions of the object
    :param box: Tuple (H, W) the dimensions of the box.
    :return: Tuple
    """
    # TODO: Code has been removed from here. 

cp/ex07/code_shift.py

0 → 100644
+11 −0
Original line number Diff line number Diff line
"""Exercise 7.7: Code shift."""

def code_shift(code : tuple, turn : tuple) -> tuple:
    """Return the updated code pattern.

    :param code: Tuple with the initial code in the lock
    :param turn: Tuple with the turn on each lock dial
    :return: Updated lock code.
    """
    # TODO: Code has been removed from here. 
    
+10 −0
Original line number Diff line number Diff line
"""Exercise 7.1: Have equal length."""

def have_equal_length(a : tuple, b : tuple) -> bool:
    """Check whether two tuples have equal length.

    :param a: Tuple.
    :param b: Tuple.
    :return: A boolean value.
    """
    # TODO: Code has been removed from here. 
+10 −0
Original line number Diff line number Diff line
"""Exercise 7.3: Last difference."""

def last_difference(a : tuple, b : tuple) -> float:
    """Return the difference between last elements regardless of length.

    :param a: The first tuple.
    :param b: The second tuple.
    :return: The difference between the last elements of the two tuples.
    """
    # TODO: Code has been removed from here. 
+9 −0
Original line number Diff line number Diff line
"""Exercise 7.8: Morse code."""

def morse_to_text(morse_code : str) -> str:
    """Return the extracted message from its Morse code.

    :param morse_code: String with the initial message encoded in Morse. 
    :return: The decoded message.
    """
    # TODO: Code has been removed from here. 
+11 −0
Original line number Diff line number Diff line
"""Exercise 7.4: Returning multiple values."""


def returning_multiple_values(values: list, threshold: int) -> tuple:
    """Return a tuple containing a list of all elements in the list that are greater than the threshold and the minimum of the values.

    :param values: A list of integers.
    :param threshold: An integer.
    :return: A tuple containing the a list of elements that are greater than the threshold and the minimum of values
    """
    # TODO: Code has been removed from here. 

cp/ex07/rgb_to_hue.py

0 → 100644
+9 −0
Original line number Diff line number Diff line
"""Exercise 7.4: Color Hue."""

def rgb_to_hue(RGB: tuple) -> float:
    """Return the hue given RGB values.

    :param RGB: Tuple containing  three RGB values.
    :return: Hue in degrees.
    """
    # TODO: Code has been removed from here. 

cp/ex08/__init__.py

0 → 100644
+1 −0
Original line number Diff line number Diff line
"""DO NOT EDIT/ADD TO THIS FILE.""" 

cp/ex08/counting.py

0 → 100644
+31 −0
Original line number Diff line number Diff line
"""Exercise 8.4: Counting."""

from cp.ex08.loading import load_txt2str

def count_words(string) -> int:
    """Count the number of words in a string.
    
    :param string: A string.
    :return: The number of words in the string.
    """
    # TODO: Code has been removed from here. 

def count_letters(string) -> int:
    """Count the number of letters in a string.
    
    :param string: A string.
    :return: The number of letters in the string without spaces.
    """
    # TODO: Code has been removed from here. 

def count_words_letters(path: str) -> tuple:
    """Count the number of words and letters in a text file.
    
    This function takes a file path as input, reads the content of the text file
    located at the specified path, and returns the number of words and letters in
    the text file as a tuple.
    
    :param path: A string representing the path to the text file.
    :return: A tuple containing the number of words and letters in the text file.
    """
    # TODO: Code has been removed from here. 
+22 −0

File added.

Preview size limit exceeded, changes collapsed.

+1406 −0

File added.

Preview size limit exceeded, changes collapsed.

+15 −0

File added.

Preview size limit exceeded, changes collapsed.

+22 −0

File added.

Preview size limit exceeded, changes collapsed.

+21 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex08/loading.py

0 → 100644
+23 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex08/save_csv.py

0 → 100644
+11 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex08/saving.py

0 → 100644
+24 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex09/__init__.py

0 → 100644
+1 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex09/rectangle.py

0 → 100644
+7 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex09/vector.py

0 → 100644
+8 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex10/__init__.py

0 → 100644
+1 −0

File added.

Preview size limit exceeded, changes collapsed.

+11 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex10/student.py

0 → 100644
+28 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex10/vector.py

0 → 100644
+13 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex11/__init__.py

0 → 100644
+1 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex11/outliers.py

0 → 100644
+11 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex12/__init__.py

0 → 100644
+1 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex12/cpr_check.py

0 → 100644
+9 −0

File added.

Preview size limit exceeded, changes collapsed.

cp/ex12/polygon.py

0 → 100644
+10 −0

File added.

Preview size limit exceeded, changes collapsed.

+1 −0

File added.

Preview size limit exceeded, changes collapsed.

+1 −0

File added.

Preview size limit exceeded, changes collapsed.

+1 −0

File added.

Preview size limit exceeded, changes collapsed.

+1 −0

File added.

Preview size limit exceeded, changes collapsed.

+1 −0

File added.

Preview size limit exceeded, changes collapsed.

File changed.

Preview size limit exceeded, changes collapsed.

cp/tests/tests_week01.py

deleted100644 → 0
+0 −64

File deleted.

Preview size limit exceeded, changes collapsed.

File changed.

Preview size limit exceeded, changes collapsed.