Compare commits
5
Commits
45921bfe17
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aea0c0173d | ||
|
|
eb6a242257 | ||
|
|
f03c720435 | ||
|
|
0b02a65bd4 | ||
|
|
f089317e86 |
No files matched your search
@@ -13,6 +13,6 @@ repos:
|
|||||||
- id: ruff # Linting
|
- id: ruff # Linting
|
||||||
|
|
||||||
- repo: https://github.com/psf/black
|
- repo: https://github.com/psf/black
|
||||||
rev: stable
|
rev: 26.3.1
|
||||||
hooks:
|
hooks:
|
||||||
- id: black # formatting
|
- id: black # formatting
|
||||||
@@ -2,7 +2,6 @@ import typing
|
|||||||
|
|
||||||
|
|
||||||
class Router(object):
|
class Router(object):
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.routes = {}
|
self.routes = {}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,303 @@
|
|||||||
|
PERIODIC_TABLE: dict[str, tuple[int, float | int]] = {
|
||||||
|
"H": (1, 1.0),
|
||||||
|
"B": (3, 10.8),
|
||||||
|
"C": (4, 12.0),
|
||||||
|
"N": (3, 14.0),
|
||||||
|
"O": (2, 16.0),
|
||||||
|
"F": (1, 19.0),
|
||||||
|
"Mg": (2, 24.3),
|
||||||
|
"P": (3, 31.0),
|
||||||
|
"S": (2, 32.1),
|
||||||
|
"Cl": (1, 35.5),
|
||||||
|
"Br": (1, 80.0),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class LockedMolecule(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class UnlockedMolecule(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidBond(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class EmptyMolecule(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Atom(object):
|
||||||
|
def __init__(self, elt: str, id_: int):
|
||||||
|
self.element = elt
|
||||||
|
self.id = id_
|
||||||
|
self.bounds = []
|
||||||
|
self.max_bounds = PERIODIC_TABLE[self.element][0]
|
||||||
|
self.weight = PERIODIC_TABLE[self.element][1]
|
||||||
|
|
||||||
|
def __hash__(self):
|
||||||
|
return self.id
|
||||||
|
|
||||||
|
def __eq__(self, other):
|
||||||
|
return self.id == other.id
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
bounds = []
|
||||||
|
|
||||||
|
bounds.extend(
|
||||||
|
list(sorted(Molecule.filter_element(self.bounds, "C"), key=lambda b: b.id))
|
||||||
|
)
|
||||||
|
bounds.extend(
|
||||||
|
list(sorted(Molecule.filter_element(self.bounds, "O"), key=lambda b: b.id))
|
||||||
|
)
|
||||||
|
|
||||||
|
for bound in list(
|
||||||
|
sorted(sorted(self.bounds, key=lambda b: b.id), key=lambda b: b.element)
|
||||||
|
):
|
||||||
|
if bound.element not in ["C", "H", "O"]:
|
||||||
|
bounds.append(bound)
|
||||||
|
|
||||||
|
bounds.extend(
|
||||||
|
list(sorted(Molecule.filter_element(self.bounds, "H"), key=lambda b: b.id))
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
f"Atom({self.element}.{self.id}"
|
||||||
|
f"{': ' if bounds else ''}"
|
||||||
|
f"{','.join(bound.element + (str(bound.id) if bound.element != 'H' else '') for bound in bounds)})"
|
||||||
|
)
|
||||||
|
|
||||||
|
def add_bound(self, atom):
|
||||||
|
if self == atom:
|
||||||
|
raise InvalidBond
|
||||||
|
if len(self.bounds) >= self.max_bounds:
|
||||||
|
raise InvalidBond
|
||||||
|
|
||||||
|
self.bounds.append(atom)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def remove_bounds(atom1, atom2):
|
||||||
|
if not (atom1 or atom2):
|
||||||
|
return
|
||||||
|
|
||||||
|
if atom1 in atom2.bounds:
|
||||||
|
atom2.bounds.remove(atom1)
|
||||||
|
|
||||||
|
if atom2 in atom1.bounds:
|
||||||
|
atom1.bounds.remove(atom2)
|
||||||
|
|
||||||
|
def mutate(self, element: str):
|
||||||
|
if len(self.bounds) > PERIODIC_TABLE[element][0]:
|
||||||
|
raise InvalidBond
|
||||||
|
|
||||||
|
self.element = element
|
||||||
|
self.max_bounds = PERIODIC_TABLE[self.element][0]
|
||||||
|
self.weight = PERIODIC_TABLE[self.element][1]
|
||||||
|
|
||||||
|
def unlock(self):
|
||||||
|
self.bounds = list(filter(lambda atom: atom.element != "H", self.bounds))
|
||||||
|
|
||||||
|
|
||||||
|
class Molecule(object):
|
||||||
|
name: str
|
||||||
|
_formula: str
|
||||||
|
_molecular_weight: float
|
||||||
|
atoms: list[Atom]
|
||||||
|
branches: dict[int, list[Atom]]
|
||||||
|
locked: bool = False
|
||||||
|
exception_thrown = False
|
||||||
|
|
||||||
|
def __init__(self, name=""):
|
||||||
|
self.name = name
|
||||||
|
self.atoms = []
|
||||||
|
self.branches = {}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def filter_element(atoms: list[Atom], element: str) -> list[Atom]:
|
||||||
|
return list(filter(lambda atom: element == atom.element, atoms))
|
||||||
|
|
||||||
|
def brancher(self, *branches: int):
|
||||||
|
if self.locked:
|
||||||
|
raise LockedMolecule
|
||||||
|
|
||||||
|
for carbons in branches:
|
||||||
|
branch_id = len(self.branches) + 1
|
||||||
|
self.branches[branch_id] = []
|
||||||
|
for i in range(1, carbons + 1):
|
||||||
|
atom = Atom(elt="C", id_=len(self.atoms) + i)
|
||||||
|
self.branches[branch_id].append(atom)
|
||||||
|
|
||||||
|
if i > 1:
|
||||||
|
last_atom = self.branches[branch_id][i - 2]
|
||||||
|
|
||||||
|
try:
|
||||||
|
atom.add_bound(last_atom)
|
||||||
|
last_atom.add_bound(atom)
|
||||||
|
except InvalidBond as e:
|
||||||
|
Atom.remove_bounds(atom, last_atom)
|
||||||
|
raise e
|
||||||
|
|
||||||
|
self.atoms.extend(self.branches[branch_id])
|
||||||
|
return self
|
||||||
|
|
||||||
|
def bounder(self, *bounds: tuple[int, int, int, int]):
|
||||||
|
if self.locked:
|
||||||
|
raise LockedMolecule
|
||||||
|
|
||||||
|
for c1, b1, c2, b2 in bounds:
|
||||||
|
atom1 = self.branches[b1][c1 - 1]
|
||||||
|
atom2 = self.branches[b2][c2 - 1]
|
||||||
|
|
||||||
|
atom1_bounds = atom1.bounds[:]
|
||||||
|
atom2_bounds = atom2.bounds[:]
|
||||||
|
|
||||||
|
try:
|
||||||
|
atom1.add_bound(atom2)
|
||||||
|
atom2.add_bound(atom1)
|
||||||
|
except InvalidBond as e:
|
||||||
|
atom1.bounds = atom1_bounds
|
||||||
|
atom2.bounds = atom2_bounds
|
||||||
|
raise e
|
||||||
|
|
||||||
|
return self
|
||||||
|
|
||||||
|
def mutate(self, *mutations: tuple[int, int, str]):
|
||||||
|
if self.locked:
|
||||||
|
raise LockedMolecule
|
||||||
|
|
||||||
|
for nc, nb, element in mutations:
|
||||||
|
atom = self.branches[nb][nc - 1]
|
||||||
|
try:
|
||||||
|
atom.mutate(element)
|
||||||
|
except InvalidBond as e:
|
||||||
|
raise e
|
||||||
|
|
||||||
|
return self
|
||||||
|
|
||||||
|
def add(self, *additions: tuple[int, int, str]):
|
||||||
|
if self.locked:
|
||||||
|
raise LockedMolecule
|
||||||
|
|
||||||
|
for nc, nb, element in additions:
|
||||||
|
atom = Atom(elt=element, id_=len(self.atoms) + 1)
|
||||||
|
carbon = self.branches[nb][nc - 1]
|
||||||
|
|
||||||
|
try:
|
||||||
|
carbon.add_bound(atom)
|
||||||
|
atom.add_bound(carbon)
|
||||||
|
except InvalidBond as e:
|
||||||
|
Atom.remove_bounds(carbon, atom)
|
||||||
|
raise e
|
||||||
|
|
||||||
|
self.atoms.append(atom)
|
||||||
|
|
||||||
|
return self
|
||||||
|
|
||||||
|
def add_chaining(self, nc: int, nb: int, *elements: str):
|
||||||
|
if self.locked:
|
||||||
|
raise LockedMolecule
|
||||||
|
|
||||||
|
carbon = self.branches[nb][nc - 1]
|
||||||
|
|
||||||
|
chain = []
|
||||||
|
|
||||||
|
try:
|
||||||
|
last_atom = Atom(elt=elements[0], id_=len(self.atoms) + len(chain) + 1)
|
||||||
|
chain.append(last_atom)
|
||||||
|
|
||||||
|
for element in elements[1:]:
|
||||||
|
atom = Atom(elt=element, id_=len(self.atoms) + len(chain) + 1)
|
||||||
|
chain.append(atom)
|
||||||
|
last_atom.add_bound(atom)
|
||||||
|
atom.add_bound(last_atom)
|
||||||
|
last_atom = atom
|
||||||
|
except InvalidBond as e:
|
||||||
|
Atom.remove_bounds(atom, last_atom)
|
||||||
|
raise e
|
||||||
|
|
||||||
|
try:
|
||||||
|
carbon.add_bound(chain[0])
|
||||||
|
chain[0].add_bound(carbon)
|
||||||
|
except InvalidBond as e:
|
||||||
|
Atom.remove_bounds(carbon, chain[0])
|
||||||
|
raise e
|
||||||
|
|
||||||
|
self.atoms.extend(chain)
|
||||||
|
|
||||||
|
return self
|
||||||
|
|
||||||
|
def closer(self):
|
||||||
|
if self.locked:
|
||||||
|
raise LockedMolecule
|
||||||
|
|
||||||
|
try:
|
||||||
|
for atom in self.atoms:
|
||||||
|
while len(atom.bounds) < atom.max_bounds:
|
||||||
|
hydrogen = Atom(elt="H", id_=len(self.atoms) + 1)
|
||||||
|
atom.add_bound(hydrogen)
|
||||||
|
hydrogen.add_bound(atom)
|
||||||
|
self.atoms.append(hydrogen)
|
||||||
|
except InvalidBond as e:
|
||||||
|
Atom.remove_bounds(atom, hydrogen)
|
||||||
|
raise e
|
||||||
|
|
||||||
|
self.locked = True
|
||||||
|
|
||||||
|
return self
|
||||||
|
|
||||||
|
def unlock(self):
|
||||||
|
self.locked = False
|
||||||
|
self.atoms = list(filter(lambda atom: atom.element != "H", self.atoms))
|
||||||
|
|
||||||
|
for new_id, atom in enumerate(self.atoms, start=1):
|
||||||
|
atom.unlock()
|
||||||
|
atom.id = new_id
|
||||||
|
|
||||||
|
new_branches = {}
|
||||||
|
new_id = 1
|
||||||
|
for atoms in self.branches.values():
|
||||||
|
filtered = list(filter(lambda atom: atom.element != "H", atoms))
|
||||||
|
if len(filtered) > 0:
|
||||||
|
new_branches[new_id] = filtered
|
||||||
|
new_id += 1
|
||||||
|
|
||||||
|
self.branches = new_branches
|
||||||
|
|
||||||
|
if not self.branches:
|
||||||
|
raise EmptyMolecule
|
||||||
|
|
||||||
|
return self
|
||||||
|
|
||||||
|
@property
|
||||||
|
def formula(self) -> str:
|
||||||
|
if not self.locked:
|
||||||
|
raise UnlockedMolecule
|
||||||
|
|
||||||
|
elements = set(atom.element for atom in self.atoms)
|
||||||
|
formula = ""
|
||||||
|
|
||||||
|
if "C" in elements:
|
||||||
|
c_len = len(Molecule.filter_element(self.atoms, "C"))
|
||||||
|
formula += f"C{c_len if c_len > 1 else ''}"
|
||||||
|
if "H" in elements:
|
||||||
|
h_len = len(Molecule.filter_element(self.atoms, "H"))
|
||||||
|
formula += f"H{h_len if h_len > 1 else ''}"
|
||||||
|
if "O" in elements:
|
||||||
|
o_len = len(Molecule.filter_element(self.atoms, "O"))
|
||||||
|
formula += f"O{o_len if o_len > 1 else ''}"
|
||||||
|
|
||||||
|
for element in list(sorted(elements)):
|
||||||
|
if element not in ["C", "H", "O"]:
|
||||||
|
num = len(Molecule.filter_element(self.atoms, element))
|
||||||
|
formula += f"{element}{num if num > 1 else ''}"
|
||||||
|
|
||||||
|
return formula
|
||||||
|
|
||||||
|
@property
|
||||||
|
def molecular_weight(self) -> float:
|
||||||
|
if not self.locked:
|
||||||
|
raise UnlockedMolecule
|
||||||
|
|
||||||
|
return sum(atom.weight for atom in self.atoms)
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
class VigenereCipher(object):
|
||||||
|
def __init__(self, key: str, alphabet: str):
|
||||||
|
self.key = key
|
||||||
|
self.alphabet = alphabet
|
||||||
|
|
||||||
|
def encode(self, text):
|
||||||
|
encoded_text = ""
|
||||||
|
|
||||||
|
for idx, c in enumerate(text):
|
||||||
|
alph_position = self.alphabet.find(c)
|
||||||
|
if alph_position == -1:
|
||||||
|
encoded_text += c
|
||||||
|
continue
|
||||||
|
shift = self.alphabet.find(self.key[idx % len(self.key)])
|
||||||
|
|
||||||
|
encoded_text += self.alphabet[(alph_position + shift) % len(self.alphabet)]
|
||||||
|
|
||||||
|
return encoded_text
|
||||||
|
|
||||||
|
def decode(self, text):
|
||||||
|
encoded_text = ""
|
||||||
|
|
||||||
|
for idx, c in enumerate(text):
|
||||||
|
alph_position = self.alphabet.find(c)
|
||||||
|
if alph_position == -1:
|
||||||
|
encoded_text += c
|
||||||
|
continue
|
||||||
|
shift = self.alphabet.find(self.key[idx % len(self.key)])
|
||||||
|
|
||||||
|
encoded_text += self.alphabet[(alph_position - shift) % len(self.alphabet)]
|
||||||
|
|
||||||
|
return encoded_text
|
||||||
@@ -72,3 +72,5 @@ print(dog2.bark(3))
|
|||||||
print(dog2.is_puppy())
|
print(dog2.is_puppy())
|
||||||
print(Dog.amount_of_dogs)
|
print(Dog.amount_of_dogs)
|
||||||
print(dog2 == dog1)
|
print(dog2 == dog1)
|
||||||
|
|
||||||
|
print("is a dog", isinstance(dog1, Dog))
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Protocol
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class CodeWarsUser:
|
||||||
|
username: str
|
||||||
|
|
||||||
|
|
||||||
|
class UserFetcher(Protocol):
|
||||||
|
@staticmethod
|
||||||
|
def get_user(username: str) -> CodeWarsUser:
|
||||||
|
return CodeWarsUser(username)
|
||||||
|
|
||||||
|
|
||||||
|
class CodewarsAdapter:
|
||||||
|
@staticmethod
|
||||||
|
def get_user(username: str) -> CodeWarsUser:
|
||||||
|
return CodeWarsUser(username)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeAdapter:
|
||||||
|
@staticmethod
|
||||||
|
def get_user(username: str) -> CodeWarsUser:
|
||||||
|
return CodeWarsUser(username)
|
||||||
|
|
||||||
|
|
||||||
|
class WrongAdapter:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
fetchers: list = []
|
||||||
|
|
||||||
|
fetchers.append(CodewarsAdapter())
|
||||||
|
fetchers.append(FakeAdapter())
|
||||||
|
fetchers.append(WrongAdapter())
|
||||||
|
|
||||||
|
for fetcher in fetchers:
|
||||||
|
print(fetcher.get_user("user name"))
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
def discount_price(price: float, discount: float) -> float:
|
||||||
|
if price < 0:
|
||||||
|
raise ValueError("price cannot be negative")
|
||||||
|
if not 0 <= discount <= 100:
|
||||||
|
raise ValueError("discount must be between 0 and 100")
|
||||||
|
return price - (price * discount / 100)
|
||||||
@@ -208,7 +208,6 @@ def main() -> None:
|
|||||||
]
|
]
|
||||||
|
|
||||||
for filename in files:
|
for filename in files:
|
||||||
|
|
||||||
BASE_DIR = Path(__file__).parent
|
BASE_DIR = Path(__file__).parent
|
||||||
file_path = BASE_DIR / "data" / filename
|
file_path = BASE_DIR / "data" / filename
|
||||||
|
|
||||||
|
|||||||
Whitespace-only changes.
@@ -0,0 +1,16 @@
|
|||||||
|
# Task: Schreibt für die folgende Aufgabe einige Unit-Test. Nutzt dazu für den Happy-Path einen parametrisierten Test für
|
||||||
|
# einige valide Inputs und Outputs
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_bmi(weight_kg: float, height_m: float) -> float:
|
||||||
|
"""
|
||||||
|
Berechnet den Body Mass Index (BMI).
|
||||||
|
BMI = Gewicht (kg) / Grösse (m)^2
|
||||||
|
"""
|
||||||
|
if weight_kg <= 0 or height_m <= 0:
|
||||||
|
raise ValueError("Gewicht und Grösse müssen positiv sein.")
|
||||||
|
return weight_kg / (height_m**2)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print(calculate_bmi(weight_kg=72, height_m=1.84))
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# TASK: Schreibe sinnvolle Tests für die folgende Funktion
|
||||||
|
# Schreibe Tests für die korrekte Struktur des Outputs der Funktion
|
||||||
|
# Teste, ob bei Übergabe von 'falschem' Parameter data eine Exception geworfen wird
|
||||||
|
|
||||||
|
# https://docs.python.org/3/library/exceptions.html
|
||||||
|
# Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError,
|
||||||
|
# but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.
|
||||||
|
|
||||||
|
|
||||||
|
def double_integers(data: list[int]) -> list[int]:
|
||||||
|
"""Doubles a list of given integers
|
||||||
|
|
||||||
|
:param data: list of integers
|
||||||
|
:return: list of doubled integers
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not isinstance(data, list):
|
||||||
|
raise TypeError("data must be a list")
|
||||||
|
if not all([isinstance(i, int) for i in data]):
|
||||||
|
raise TypeError("data may contain only integers")
|
||||||
|
|
||||||
|
return [i * 2 for i in data]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
data = [1, 2, 3]
|
||||||
|
result = double_integers(data)
|
||||||
|
print(result)
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# https://www.codewars.com/kata/53dbd5315a3c69eed20002dd
|
||||||
|
# level: 7 kyu
|
||||||
|
|
||||||
|
# In this kata you will create a function that takes a list of non-negative integers and strings and returns a new
|
||||||
|
# list with the strings filtered out.
|
||||||
|
#
|
||||||
|
# Example
|
||||||
|
# filter_list([1,2,'a','b']) == [1,2]
|
||||||
|
# filter_list([1,'a','b',0,15]) == [1,0,15]
|
||||||
|
# filter_list([1,2,'aasf','1','123',123]) == [1,2,123]
|
||||||
|
|
||||||
|
|
||||||
|
def filter_list(input_list):
|
||||||
|
if not isinstance(input_list, list):
|
||||||
|
return []
|
||||||
|
return [i for i in input_list if not isinstance(i, bool) and isinstance(i, int)]
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# https://www.codewars.com/kata/5ea2baed9345eb001e8ce394
|
||||||
|
# 7 kyu
|
||||||
|
|
||||||
|
# Input parameters
|
||||||
|
|
||||||
|
# dataframe: pandas.DataFrame object
|
||||||
|
# col: target column
|
||||||
|
# func: filter function
|
||||||
|
|
||||||
|
# Task
|
||||||
|
# Your function must return a new pandas.DataFrame object with the same columns as the original input. However,
|
||||||
|
# include only the rows whose cell values in the designated column evaluate to False by func.
|
||||||
|
#
|
||||||
|
# Input DataFrame will never be empty. The target column will always be one of the dataframe columns. Filter function
|
||||||
|
# will be a valid one. Index value must remain the same.
|
||||||
|
|
||||||
|
# REMARK: leichte Modifikation -> es wird ausgegeben, was in der Funktion definiert wurde (True) und nicht umgekehrt.
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
|
||||||
|
def filter_dataframe(df, col, func):
|
||||||
|
if col not in df.columns:
|
||||||
|
raise ValueError(f"Column '{col}' is not present in the DataFrame.")
|
||||||
|
mask = df[col].apply(func)
|
||||||
|
return df[mask]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
df = pd.DataFrame(
|
||||||
|
{
|
||||||
|
"A": list(range(0, 10)),
|
||||||
|
"B": list(range(-5, 5)),
|
||||||
|
"C": list(range(-2, 8)),
|
||||||
|
"D": list(range(10, 20)),
|
||||||
|
"E": list(range(-20, -10)),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
print(filter_dataframe(df, "A", lambda x: x >= 4))
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# https://www.codewars.com/kata/54ff3102c1bad923760001f3
|
||||||
|
# level: 7 kyu
|
||||||
|
|
||||||
|
# Return the number (count) of vowels in the given string.
|
||||||
|
# We will consider a, e, i, o, u as vowels for this Kata (but not y).
|
||||||
|
# The input string will only consist of lower case letters and/or spaces.
|
||||||
|
|
||||||
|
|
||||||
|
def get_count(inputStr):
|
||||||
|
num_vowels = 0
|
||||||
|
for char in inputStr:
|
||||||
|
if char in "aeiouAEIOU":
|
||||||
|
num_vowels = num_vowels + 1
|
||||||
|
return num_vowels
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print(get_count("Hello World"))
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from src.exercises.pricing import discount_price
|
||||||
|
|
||||||
|
|
||||||
|
def test_discount_price_happy_path():
|
||||||
|
result = discount_price(100.0, 20.0)
|
||||||
|
assert result == 80.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_discount_price_edge_case_1():
|
||||||
|
result = discount_price(100.0, 100.0)
|
||||||
|
assert result == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_discount_price_edge_case_2():
|
||||||
|
result = discount_price(100.0, 0.0)
|
||||||
|
assert result == 100.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_discount_price_negative_price():
|
||||||
|
with pytest.raises(ValueError, match="price cannot be negative"):
|
||||||
|
discount_price(-1.0, 20.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_discount_price_invalid_discount():
|
||||||
|
with pytest.raises(ValueError, match="discount must be between 0 and 100"):
|
||||||
|
discount_price(100.0, 120.0)
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
from src.moduleA import addition
|
from src.exercises.moduleA import addition
|
||||||
|
|
||||||
|
|
||||||
def test_a():
|
def test_a():
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import pytest
|
||||||
|
from testing.catching_exeptions import double_integers
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"data, expected_error",
|
||||||
|
[
|
||||||
|
(123, "data must be a list"),
|
||||||
|
([1, "2", 3, 4, 5], "data may contain only integers"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_double_integers_unhappy_path(data, expected_error) -> None:
|
||||||
|
with pytest.raises(TypeError, match=expected_error):
|
||||||
|
double_integers(data)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"data, expected_result",
|
||||||
|
[
|
||||||
|
([1, 2, 3, 4, 5], [2, 4, 6, 8, 10]),
|
||||||
|
([0, -1, -2, -3, -4, -5], [0, -2, -4, -6, -8, -10]),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_double_integers_happy_path(data, expected_result) -> None:
|
||||||
|
assert double_integers(data) == expected_result
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import pytest
|
||||||
|
from testing.kata_list_filtering import filter_list
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"input_list,expected_result",
|
||||||
|
[
|
||||||
|
([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]),
|
||||||
|
([], []),
|
||||||
|
([1 / 2, 1, "2", 3, "4", 5], [1, 3, 5]),
|
||||||
|
(["1", "2", "3", "4", "5"], []),
|
||||||
|
([True, False], []),
|
||||||
|
(1, []),
|
||||||
|
("asd123", []),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_filter_list(input_list, expected_result) -> None:
|
||||||
|
assert filter_list(input_list) == expected_result
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import pytest
|
||||||
|
import pandas as pd
|
||||||
|
from testing.pandas_filter_rows import filter_dataframe
|
||||||
|
|
||||||
|
# --- Fixtures ---
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def sample_df():
|
||||||
|
return pd.DataFrame(
|
||||||
|
{
|
||||||
|
"age": [10, 25, 35, 45],
|
||||||
|
"name": ["Alice", "Bob", "Charlie", "Diana"],
|
||||||
|
"score": [88.5, 92.0, 70.0, 55.5],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --- Happy path tests ---
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_numeric_column(sample_df):
|
||||||
|
result = filter_dataframe(sample_df, "age", lambda x: x > 20)
|
||||||
|
assert list(result["age"]) == [25, 35, 45]
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_returns_dataframe(sample_df):
|
||||||
|
result = filter_dataframe(sample_df, "age", lambda x: x > 0)
|
||||||
|
assert isinstance(result, pd.DataFrame)
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_string_column(sample_df):
|
||||||
|
result = filter_dataframe(sample_df, "name", lambda x: x.startswith("A"))
|
||||||
|
assert list(result["name"]) == ["Alice"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_float_column(sample_df):
|
||||||
|
result = filter_dataframe(sample_df, "score", lambda x: x >= 88.5)
|
||||||
|
assert list(result["score"]) == [88.5, 92.0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_preserves_all_columns(sample_df):
|
||||||
|
result = filter_dataframe(sample_df, "age", lambda x: x == 25)
|
||||||
|
assert list(result.columns) == ["age", "name", "score"]
|
||||||
|
assert result.iloc[0]["name"] == "Bob"
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_preserves_original_index(sample_df):
|
||||||
|
result = filter_dataframe(sample_df, "age", lambda x: x > 30)
|
||||||
|
assert list(result.index) == [2, 3]
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_does_not_mutate_original(sample_df):
|
||||||
|
original_len = len(sample_df)
|
||||||
|
filter_dataframe(sample_df, "age", lambda x: x > 20)
|
||||||
|
assert len(sample_df) == original_len
|
||||||
|
|
||||||
|
|
||||||
|
# --- Edge cases ---
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_all_rows_pass(sample_df):
|
||||||
|
result = filter_dataframe(sample_df, "age", lambda x: x > 0)
|
||||||
|
assert len(result) == len(sample_df)
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_no_rows_pass(sample_df):
|
||||||
|
result = filter_dataframe(sample_df, "age", lambda x: x > 1000)
|
||||||
|
assert len(result) == 0
|
||||||
|
assert list(result.columns) == ["age", "name", "score"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_on_empty_dataframe():
|
||||||
|
empty_df = pd.DataFrame({"age": [], "name": []})
|
||||||
|
result = filter_dataframe(empty_df, "age", lambda x: x > 10)
|
||||||
|
assert len(result) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_with_none_values():
|
||||||
|
df = pd.DataFrame({"value": [1, None, 3, None]})
|
||||||
|
result = filter_dataframe(df, "value", lambda x: x is not None and x > 1)
|
||||||
|
assert list(result["value"]) == [3.0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_single_row_match():
|
||||||
|
df = pd.DataFrame({"x": [42]})
|
||||||
|
result = filter_dataframe(df, "x", lambda x: x == 42)
|
||||||
|
assert len(result) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_single_row_no_match():
|
||||||
|
df = pd.DataFrame({"x": [42]})
|
||||||
|
result = filter_dataframe(df, "x", lambda x: x == 0)
|
||||||
|
assert len(result) == 0
|
||||||
|
|
||||||
|
|
||||||
|
# --- Error handling ---
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_column_raises_value_error(sample_df):
|
||||||
|
with pytest.raises(ValueError, match="Column 'missing' is not present"):
|
||||||
|
filter_dataframe(sample_df, "missing", lambda x: x > 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_column_error_message_includes_column_name(sample_df):
|
||||||
|
with pytest.raises(ValueError, match="nonexistent"):
|
||||||
|
filter_dataframe(sample_df, "nonexistent", lambda x: True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_func_exception_propagates(sample_df):
|
||||||
|
def bad_func(x):
|
||||||
|
raise RuntimeError("Intentional error")
|
||||||
|
|
||||||
|
with pytest.raises(RuntimeError, match="Intentional error"):
|
||||||
|
filter_dataframe(sample_df, "age", bad_func)
|
||||||
Reference in new issue
Block a user