add collatz exercise, simplify names, update readme
This commit is contained in:
30
collatz/collatz.py
Normal file
30
collatz/collatz.py
Normal file
@@ -0,0 +1,30 @@
|
||||
import readline
|
||||
|
||||
class CollatzCalculator:
|
||||
def calculate_steps(self, n: int) -> int:
|
||||
if n <= 1:
|
||||
return 0
|
||||
steps = 0
|
||||
while n != 1:
|
||||
if n % 2 == 0:
|
||||
n //= 2
|
||||
print(f"Step #{steps + 1}: even, divide by 2 -> {n}")
|
||||
else:
|
||||
n = 3 * n + 1
|
||||
print(f"Step #{steps + 1}: odd, multiply by 3 and add 1 -> {n}")
|
||||
steps += 1
|
||||
return steps + 1
|
||||
|
||||
def main():
|
||||
calculator = CollatzCalculator()
|
||||
while True:
|
||||
try:
|
||||
n = input("Please enter a whole number: ")
|
||||
print(f"Result: {calculator.calculate_steps(int(n))} steps needed to reach {n}")
|
||||
except ValueError:
|
||||
print("ERROR: integer required")
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
break
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
27
collatz/test_collatz.py
Normal file
27
collatz/test_collatz.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import pytest
|
||||
from collatz import CollatzCalculator
|
||||
|
||||
def test_calculate_steps_for_1():
|
||||
calc = CollatzCalculator()
|
||||
assert calc.calculate_steps(1) == 0
|
||||
|
||||
def test_calculate_steps_for_2():
|
||||
calc = CollatzCalculator()
|
||||
assert calc.calculate_steps(2) == 2 # 2 -> 1 (even), returns 2 steps
|
||||
|
||||
def test_calculate_steps_for_3():
|
||||
calc = CollatzCalculator()
|
||||
assert calc.calculate_steps(3) == 8 # 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
|
||||
|
||||
def test_calculate_steps_for_6():
|
||||
calc = CollatzCalculator()
|
||||
assert calc.calculate_steps(6) == 9 # 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
|
||||
|
||||
def test_calculate_steps_for_large_number():
|
||||
calc = CollatzCalculator()
|
||||
assert calc.calculate_steps(27) == 112
|
||||
|
||||
def test_calculate_steps_for_zero_and_negative():
|
||||
calc = CollatzCalculator()
|
||||
assert calc.calculate_steps(0) == 0
|
||||
assert calc.calculate_steps(-5) == 0
|
||||
Reference in New Issue
Block a user