Python O(n) sol. by threading.Lock 90%+ [ With hint and comment ]
Python O(n) sol. by threading.Lock\n\n---\n\nHint:\n\n#1.\nDraw some simple cases to catch the order of mutex locking / unlocking.\n\n#2.\nNeed one mutex for pr
Python O(n) sol. by threading.Lock\n\n---\n\n**Hint**:\n\n#1.\nDraw some simple cases to catch the order of mutex locking / unlocking.\n\n#2.\nNeed one mutex for printing \'0\' threading control,\nanother one for printing odd numbers,\nthe last one for printing even numbers.\n\n#3.\nAPI has offered *printNumber*( *x*: int) for us to print an integer, value is assigned by parameter *x*.\n\n---\n\n```\nfrom threading import Lock\n\nclass ZeroEvenOdd:\n    def __init__(self, n):\n        self.n = n\n        \n        self.zero_mutex = Lock()\n        self.odd_mutex = Lock()\n        self.even_mutex = Lock()\n        \n        # Lock mutex for even number and odd number, \n        # because 0 must be printed first\n        self.even_mutex.acquire()\n        self.odd_mutex.acquire()\n        \n        \n\t# printNumber(x) outputs "x", where x is an integer.\n    def zero(self, printNumber: \'Callable[[int], None]\') -> None:\n        \n        for i in range(1, self.n+1):\n\n            # lock mutex for zero\n            self.zero_mutex.acquire()\n            \n            printNumber(0)\n            \n\n            if ( i % 2 )== 1:\n                # unlock mutex for odd number\n                self.odd_mutex.release()\n            else:\n                # unlock mutex for even number\n                self.even_mutex.release()\n\n    def even(self, printNumber: \'Callable[[int], None]\') -> None:\n        \n        for j in range(2, self.n+1, 2):\n\n            # lock mutex for even number\n            self.even_mutex.acquire()\n            \n            printNumber(j)\n            \n            # unlock mutex for zero\n            self.zero_mutex.release()\n        \n        \n    def odd(self, printNumber: \'Callable[[int], None]\') -> None:\n        \n        for k in range(1, self.n+1, 2):\n            \n            # lock mutex for odd number\n            self.odd_mutex.acquire()\n            \n            printNumber(k)\n            \n            # unlock mutex for zero\n            self.zero_mutex.release()\n```\n\n---\n\nReference:\n\n[1] [Python official docs about threading.Lock()](https://docs.python.org/3.8/library/threading.html#lock-objects)\n\n[2] [Wiki: Lock and Mutex](https://en.wikipedia.org/wiki/Lock_(computer_science))
['Python']