- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 49 lines of Python from the credited upstream file 1195.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from threading import Semaphore2 3 4class FizzBuzz:5 def __init__(self, n: int):6 self.n = n7 self.fizzSemaphore = Semaphore(0)8 self.buzzSemaphore = Semaphore(0)9 self.fizzbuzzSemaphore = Semaphore(0)10 self.numberSemaphore = Semaphore(1)11 12 13 def fizz(self, printFizz: 'Callable[[], None]') -> None:14 for i in range(1, self.n + 1):15 if i % 3 == 0 and i % 15 != 0:16 self.fizzSemaphore.acquire()17 printFizz()18 self.numberSemaphore.release()19 20 21 def buzz(self, printBuzz: 'Callable[[], None]') -> None:22 for i in range(1, self.n + 1):23 if i % 5 == 0 and i % 15 != 0:24 self.buzzSemaphore.acquire()25 printBuzz()26 self.numberSemaphore.release()27 28 29 def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None:30 for i in range(1, self.n + 1):31 if i % 15 == 0:32 self.fizzbuzzSemaphore.acquire()33 printFizzBuzz()34 self.numberSemaphore.release()35 36 37 def number(self, printNumber: 'Callable[[int], None]') -> None:38 for i in range(1, self.n + 1):39 self.numberSemaphore.acquire()40 if i % 15 == 0:41 self.fizzbuzzSemaphore.release()42 elif i % 3 == 0:43 self.fizzSemaphore.release()44 elif i % 5 == 0:45 self.buzzSemaphore.release()46 else:47 printNumber(i)48 self.numberSemaphore.release()49