-
Notifications
You must be signed in to change notification settings - Fork 31
Fix exercises on objects #114
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
yakutovicha
wants to merge
4
commits into
main
Choose a base branch
from
fix/exercises-on-objects
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+223
−2
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
ef6724c
Fix exercise 1 on objects.
yakutovicha bf21c9c
Fixes exercise text and solution skeleton
edoardob90 7b705db
Merge branch 'main' into fix/exercises-on-objects
despadam 0b3e8b5
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,215 @@ | ||
| import pathlib | ||
| import sys | ||
|
|
||
| import pytest | ||
| from numpy import average | ||
|
|
||
| FLAVORS = [ | ||
| ("chocolate",), | ||
| ("chocolate", "vanilla", "persimmon"), | ||
| ("chocolate", "vanilla", "stracciatella"), | ||
| ("chocolate", "vanilla", "stracciatella", "strawberry"), | ||
| ("chocolate", "vanilla", "stracciatella", "strawberry", "pistachio"), | ||
| ] | ||
|
|
||
| # | ||
| # Exercise 1: Ice cream scoop | ||
| # | ||
|
|
||
|
|
||
| class Scoop: | ||
| """A class representing a single scoop of ice cream""" | ||
|
|
||
| def __init__(self, flavor: str): | ||
| self.flavor = flavor | ||
|
|
||
| def __str__(self): | ||
| return f"Ice cream scoop with flavor '{self.flavor}'" | ||
|
|
||
|
|
||
| def reference_ice_cream_scoop(flavors: tuple[str]) -> list[Scoop, str]: | ||
| return [(Scoop(flavor), str(Scoop(flavor))) for flavor in flavors] | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("flavors", FLAVORS) | ||
| def test_ice_cream_scoop(flavors, function_to_test) -> None: | ||
| test_solution = [string for _, string in function_to_test(flavors)] | ||
| reference_solution = [string for _, string in reference_ice_cream_scoop(flavors)] | ||
| assert test_solution == reference_solution | ||
|
|
||
|
|
||
| # | ||
| # Exercise 2: Ice cream bowl | ||
| # | ||
|
|
||
|
|
||
| class Bowl: | ||
| """A class representing a bowl of ice cream scoops""" | ||
|
|
||
| def __init__(self): | ||
| self.scoops = [] | ||
|
|
||
| def add_scoops(self, *new_scoops: list["Scoop"]) -> None: | ||
| for one_scoop in new_scoops: | ||
| self.scoops.append(one_scoop) | ||
|
|
||
| def __str__(self): | ||
| return f"Ice cream bowl with {', '.join(s.flavor for s in self.scoops)} scoops" | ||
|
|
||
|
|
||
| def test_ice_cream_bowl(function_to_test) -> None: | ||
| flavors = ("chocolate", "vanilla", "stracciatella") | ||
| bowl = Bowl() | ||
| scoops = [Scoop(flavor) for flavor in flavors] | ||
| bowl.add_scoops(*scoops) | ||
| assert function_to_test(flavors) == str(bowl) | ||
|
|
||
|
|
||
| # | ||
| # Exercise 3: Intcode computer | ||
| # | ||
|
|
||
|
|
||
| def read_data(name: str, data_dir: str = "data") -> pathlib.Path: | ||
| """Read input data""" | ||
| current_module = sys.modules[__name__] | ||
| return ( | ||
| pathlib.Path(current_module.__file__).parent / f"{data_dir}/{name}" | ||
| ).resolve() | ||
|
|
||
|
|
||
| class Computer: | ||
| """An Intcode computer class""" | ||
|
|
||
| def __init__(self, program: str): | ||
| self.program = [int(c.strip()) for c in program.split(",")] | ||
| self._backup = self.program[:] | ||
|
|
||
| def reset(self): | ||
| self.program = self._backup[:] | ||
|
|
||
| def run(self, pos=0): | ||
| while True: | ||
| if self.program[pos] == 99: | ||
| break | ||
| op1, op2 = ( | ||
| self.program[self.program[pos + 1]], | ||
| self.program[self.program[pos + 2]], | ||
| ) | ||
| func = self.program[pos] | ||
| self.program[self.program[pos + 3]] = op1 + op2 if func == 1 else op1 * op2 | ||
| pos += 4 | ||
|
|
||
|
|
||
| intcodes = ["1,0,0,0,99", "2,3,0,3,99", "1,1,1,4,99,5,6,0,99"] | ||
| intcodes += [read_data(f"intcode_{i}.txt").read_text() for i in (1, 2)] | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("intcode", intcodes) | ||
| def test_intcode_computer(intcode: str, function_to_test) -> None: | ||
| computer = Computer(intcode) | ||
| computer.run() | ||
| assert function_to_test(intcode) == computer.program[0] | ||
|
|
||
|
|
||
| # | ||
| # Exercise 4: The N-body problem | ||
| # | ||
|
|
||
|
|
||
| universes = [read_data(f"universe_{i}.txt").read_text() for i in (1, 2)] | ||
|
|
||
|
|
||
| class Moon: | ||
| """A class for a moon""" | ||
|
|
||
| def __init__(self, scan: str) -> None: | ||
| name, pos = scan.split(": ") | ||
| self.name = name | ||
| self.positions = [int(x[2:]) for x in pos.split(", ")] | ||
| self.velocities = [0 for _ in range(len(self.positions))] | ||
|
|
||
| def update_velocities(self, moon: "Moon") -> None: | ||
| """Update the velocity of the moon""" | ||
| for n, position in enumerate(self.positions): | ||
| if position > moon.positions[n]: | ||
| delta = -1 | ||
| elif position < moon.positions[n]: | ||
| delta = 1 | ||
| else: | ||
| delta = 0 | ||
|
|
||
| if delta: | ||
| self.velocities[n] += delta | ||
| moon.velocities[n] -= delta | ||
|
|
||
| def update_positions(self) -> None: | ||
| """Update the position of the moon""" | ||
| for n in range(len(self.positions)): | ||
| self.positions[n] += self.velocities[n] | ||
|
|
||
| @property | ||
| def abs_velocity(self) -> int: | ||
| """Return the absolute velocity of the moon""" | ||
| return sum(abs(v) for v in self.velocities) | ||
|
|
||
| @property | ||
| def abs_position(self) -> int: | ||
| """Return the absolute position of the moon""" | ||
| return sum(abs(p) for p in self.positions) | ||
|
|
||
| @property | ||
| def energy(self) -> int: | ||
| """Return the energy of the moon""" | ||
| return self.abs_position * self.abs_velocity | ||
|
|
||
| def __repr__(self) -> str: | ||
| return "{}: x={}, y={}, z={}, vx={}, vy={}, vz={}".format( | ||
| self.name, *self.positions, *self.velocities | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("moons", universes) | ||
| def test_moons(moons: str, function_to_test): | ||
| universe = [Moon(moon) for moon in moons.splitlines()] | ||
| assert function_to_test(moons) == [repr(moon) for moon in universe] | ||
|
|
||
|
|
||
| class Universe: | ||
| """A class for a universe""" | ||
|
|
||
| def __init__(self, universe_start: str) -> None: | ||
| self.moons = [Moon(moon) for moon in universe_start.splitlines()] | ||
|
|
||
| def evolve(self) -> "Universe": | ||
| """Evolve the universe""" | ||
| for n, moon_i in enumerate(self.moons[:-1]): | ||
| for moon_j in self.moons[n + 1 :]: | ||
| moon_i.update_velocities(moon_j) | ||
|
|
||
| for moon in self.moons: | ||
| moon.update_positions() | ||
|
|
||
| return self | ||
|
|
||
| @property | ||
| def energy(self) -> int: | ||
| """Return the total energy of the universe""" | ||
| return sum(moon.energy for moon in self.moons) | ||
|
|
||
| @property | ||
| def momentum(self) -> list: | ||
| """Return the momentum of the universe""" | ||
| return list( | ||
| map(sum, zip(*[moon.velocities for moon in self.moons], strict=False)) | ||
| ) | ||
|
|
||
| def __repr__(self) -> str: | ||
| return "\n".join(repr(moon) for moon in self.moons) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("universe_start", universes) | ||
| def test_n_body(universe_start: str, function_to_test) -> None: | ||
| universe = Universe(universe_start) | ||
| energy = [universe.evolve().energy for _ in range(1000)] | ||
| assert function_to_test(universe_start) == pytest.approx(average(energy)) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've been thinking about this test all afternoon (mostly). And it can be faked easily because it doesn't really enforce you to define/use the class. One can build a tuple with
(None, "<Properly formatted string>")and the test will pass.I think it's trickier that it seems to perform some checks on the actual class. One way is to parse the AST as Simone did with some FP tests, but I didn't want to implement it for the time being.
Needs some more thoughts... 💭
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You could check whether there is a class with the name
Scoopin the locals() of the function. Something like:There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's a good suggestion 👍🏻 We must change the solution and add the class inside the solution function. Or apply the same idea to the entire code of the cell.