|
| 1 | +import asyncio |
| 2 | +from aioconsole import ainput |
| 3 | + |
| 4 | +BOUND = 10**5 |
| 5 | + |
| 6 | + |
| 7 | +class Collatz: |
| 8 | + |
| 9 | + def __init__(self): |
| 10 | + self.start = 2 |
| 11 | + |
| 12 | + async def count_steps(self, start_value): |
| 13 | + steps = 0 |
| 14 | + n = start_value |
| 15 | + while n > 1: |
| 16 | + if n % 2: |
| 17 | + n = n * 3 + 1 |
| 18 | + else: |
| 19 | + n = n // 2 |
| 20 | + steps += 1 |
| 21 | + return steps |
| 22 | + |
| 23 | + def __aiter__(self): |
| 24 | + return self |
| 25 | + |
| 26 | + async def __anext__(self): |
| 27 | + steps = await self.count_steps(self.start) |
| 28 | + self.start += 1 |
| 29 | + if self.start == BOUND: |
| 30 | + raise StopAsyncIteration |
| 31 | + return steps |
| 32 | + |
| 33 | + |
| 34 | +async def length_counter(target): |
| 35 | + count = 0 |
| 36 | + # iter = Collatz().__aiter__() |
| 37 | + # running = True |
| 38 | + # while running: |
| 39 | + # try: |
| 40 | + # steps = await iter.__anext__() |
| 41 | + # except StopAsyncIteration: |
| 42 | + # running = False |
| 43 | + # else: |
| 44 | + # if steps == target: |
| 45 | + # count += 1 |
| 46 | + |
| 47 | + async for steps in Collatz(): |
| 48 | + if steps == target: |
| 49 | + count += 1 |
| 50 | + return count |
| 51 | + |
| 52 | + |
| 53 | +async def get_input(prompt): |
| 54 | + while True: |
| 55 | + n = await ainput(prompt) |
| 56 | + try: |
| 57 | + n = int(n) |
| 58 | + except ValueError: |
| 59 | + print("Value must be an integer.") |
| 60 | + continue |
| 61 | + |
| 62 | + if n <= 0: |
| 63 | + print("Value must be positive.") |
| 64 | + else: |
| 65 | + return n |
| 66 | + |
| 67 | + |
| 68 | +async def main(): |
| 69 | + print("Collatz Sequence Counter") |
| 70 | + |
| 71 | + target = await get_input("Collatz sequence length to search for: ") |
| 72 | + print(f"Searching in range 1-{BOUND}...") |
| 73 | + |
| 74 | + # length_counter_task = asyncio.create_task(length_counter(target)) |
| 75 | + # guess_task = asyncio.create_task( |
| 76 | + # get_input("How many times do you think it will appear? ") |
| 77 | + # ) |
| 78 | + |
| 79 | + # count = await length_counter_task |
| 80 | + # guess = await guess_task |
| 81 | + |
| 82 | + (guess, count) = await asyncio.gather( |
| 83 | + get_input("How many times do you think it will appear? "), |
| 84 | + length_counter(target) |
| 85 | + ) |
| 86 | + |
| 87 | + if guess == count: |
| 88 | + print("Exactly right! I'm amazed.") |
| 89 | + elif abs(guess - count) < 100: |
| 90 | + print(f"You're close! It was {count}.") |
| 91 | + else: |
| 92 | + print(f"Nope. It was {count}.") |
| 93 | + |
| 94 | + |
| 95 | +if __name__ == "__main__": |
| 96 | + # loop = asyncio.get_event_loop() |
| 97 | + # loop.run_until_complete(main()) |
| 98 | + asyncio.run(main()) |
0 commit comments