|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(1) |
| 3 | + |
| 4 | +import threading |
| 5 | + |
| 6 | + |
| 7 | +class FizzBuzz(object): |
| 8 | + def __init__(self, n): |
| 9 | + self.__n = n |
| 10 | + self.__curr = 0 |
| 11 | + self.__cv = threading.Condition() |
| 12 | + |
| 13 | + # printFizz() outputs "fizz" |
| 14 | + def fizz(self, printFizz): |
| 15 | + """ |
| 16 | + :type printFizz: method |
| 17 | + :rtype: void |
| 18 | + """ |
| 19 | + for i in xrange(1, self.__n+1): |
| 20 | + with self.__cv: |
| 21 | + while self.__curr % 4 != 0: |
| 22 | + self.__cv.wait() |
| 23 | + self.__curr += 1 |
| 24 | + if i % 3 == 0 and i % 5 != 0: |
| 25 | + printFizz() |
| 26 | + self.__cv.notify_all() |
| 27 | + |
| 28 | + # printBuzz() outputs "buzz" |
| 29 | + def buzz(self, printBuzz): |
| 30 | + """ |
| 31 | + :type printBuzz: method |
| 32 | + :rtype: void |
| 33 | + """ |
| 34 | + for i in xrange(1, self.__n+1): |
| 35 | + with self.__cv: |
| 36 | + while self.__curr % 4 != 1: |
| 37 | + self.__cv.wait() |
| 38 | + self.__curr += 1 |
| 39 | + if i % 3 != 0 and i % 5 == 0: |
| 40 | + printBuzz() |
| 41 | + self.__cv.notify_all() |
| 42 | + |
| 43 | + # printFizzBuzz() outputs "fizzbuzz" |
| 44 | + def fizzbuzz(self, printFizzBuzz): |
| 45 | + """ |
| 46 | + :type printFizzBuzz: method |
| 47 | + :rtype: void |
| 48 | + """ |
| 49 | + for i in xrange(1, self.__n+1): |
| 50 | + with self.__cv: |
| 51 | + while self.__curr % 4 != 2: |
| 52 | + self.__cv.wait() |
| 53 | + self.__curr += 1 |
| 54 | + if i % 3 == 0 and i % 5 == 0: |
| 55 | + printFizzBuzz() |
| 56 | + self.__cv.notify_all() |
| 57 | + |
| 58 | + # printNumber(x) outputs "x", where x is an integer. |
| 59 | + def number(self, printNumber): |
| 60 | + """ |
| 61 | + :type printNumber: method |
| 62 | + :rtype: void |
| 63 | + """ |
| 64 | + for i in xrange(1, self.__n+1): |
| 65 | + with self.__cv: |
| 66 | + while self.__curr % 4 != 3: |
| 67 | + self.__cv.wait() |
| 68 | + self.__curr += 1 |
| 69 | + if i % 3 != 0 and i % 5 != 0: |
| 70 | + printNumber(i) |
| 71 | + self.__cv.notify_all() |
0 commit comments