{"id":19472548,"url":"https://github.com/joric/oneliners","last_synced_at":"2025-04-25T12:31:27.285Z","repository":{"id":61692055,"uuid":"551211487","full_name":"joric/oneliners","owner":"joric","description":"A brilliant repository of fantastic, killer one-liners","archived":false,"fork":false,"pushed_at":"2025-04-20T00:20:30.000Z","size":4333,"stargazers_count":66,"open_issues_count":0,"forks_count":3,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-04-20T01:23:12.469Z","etag":null,"topics":["leetcode","one-liners","python"],"latest_commit_sha":null,"homepage":"https://leetcode.com/joric","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/joric.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-10-14T02:26:38.000Z","updated_at":"2025-04-20T00:20:33.000Z","dependencies_parsed_at":"2023-10-12T10:51:59.270Z","dependency_job_id":"8b65c87e-a72c-481d-96fa-ab80eafd488a","html_url":"https://github.com/joric/oneliners","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joric%2Foneliners","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joric%2Foneliners/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joric%2Foneliners/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joric%2Foneliners/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/joric","download_url":"https://codeload.github.com/joric/oneliners/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250817638,"owners_count":21492188,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["leetcode","one-liners","python"],"created_at":"2024-11-10T19:14:55.056Z","updated_at":"2025-04-25T12:31:27.197Z","avatar_url":"https://github.com/joric.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"## Oneliners\r\n\r\nJust FYI, this repository isn't just README.md, it's also more than a thousand solutions [here](./leetcode).\r\n\r\n### Leetcode-specific\r\n\r\nLeetcode imports modules as wildcards, so you don't have to specify module names. There are some exceptions:\r\n\r\n* Single `bisect()` without a prefix triggers `object is not callable`, use `bisect.bisect()` or `bisect_left()`.\r\n* You have to specify `re.sub` because `sub` without a prefix is `operator.sub`.\r\n* Default `pow` is `__builtins__['pow']` (supports up to 3 arguments, including the modulus), not `math.pow`.\r\n\r\nFor example, Leetcode header has `import * from itertools`, so we use `comb()` instead of `itertools.comb()`:\r\n\r\n* https://leetcode.com/problems/unique-paths\r\n\r\n```python\r\nclass Solution:\r\n    def uniquePaths(self, m: int, n: int) -\u003e int:\r\n        return comb(m+n-2, n-1)\r\n```\r\n\r\nYou can also use `__import__('module').func` for unlisted modules (namely, `numpy`, `scipy`, and `sortedcontainers`).\r\n\r\n* https://leetcode.com/problems/check-if-it-is-a-straight-line\r\n\r\n```python\r\nclass Solution:\r\n    def checkStraightLine(self, p):\r\n        return __import__('numpy').linalg.matrix_rank([[1]+x for x in p])\u003c3\r\n```\r\n\r\nSometimes you can save on casting of the return type, e.g. Leetcode autoconverted keys and mixed types to lists.\r\n\r\n* https://leetcode.com/problems/top-k-frequent-elements\r\n\r\n```python\r\n\r\nclass Solution:\r\n    def topKFrequent(self, nums: List[int], k: int) -\u003e List[int]:\r\n        return dict(Counter(nums).most_common(k))\r\n```\r\n\r\nIt also automatically evaluated generators (stopped worked in Aug 2023, `expected return type integer[]`):\r\n\r\n* https://leetcode.com/problems/counting-bits\r\n\r\n```python\r\nclass Solution:\r\n    def countBits(self, n: int) -\u003e List[int]:\r\n        return map(int.bit_count,range(n+1))\r\n```\r\n\r\nYou can also return linked list of values as `ListNode('a,b,...')`. This one is really specific, but sometimes useful.\r\n\r\n* https://leetcode.com/problems/add-two-numbers\r\n\r\n```python\r\nclass Solution:\r\n    def addTwoNumbers(self, a: Optional[ListNode], b: Optional[ListNode]) -\u003e Optional[ListNode]:\r\n        f=lambda n:n and n.val+10*f(n.next)or 0;return ListNode(','.join([*str(f(a)+f(b))][::-1]))\r\n```\r\n\r\nLeetcode also has `serialize` and `deserialize` functions for lists and trees:\r\n\r\n* https://leetcode.com/problems/reverse-linked-list\r\n\r\n```python\r\nclass Solution:\r\n    def reverseList(self, h: Optional[ListNode]) -\u003e Optional[ListNode]:\r\n        return h and h.deserialize(str(eval(h.serialize(h))[::-1]))\r\n```\r\n\r\nThere is also `has_sycle` function:\r\n\r\n* https://leetcode.com/problems/linked-list-cycle\r\n\r\n```python\r\nclass Solution:\r\n    def hasCycle (self, h: Optional[ListNode]) -\u003e bool:\r\n        return ListNode.has_cycle(h)\r\n```\r\n\r\nThere are also `_*_node_to_array` and `_array_to_*_node` functions:\r\n\r\n* https://leetcode.com/problems/palindrome-linked-list\r\n\r\n```python\r\nclass Solution:\r\n    def isPalindrome(self, h: ListNode) -\u003e bool:\r\n        return(s:=type(h)._list_node_to_array(h))==s[::-1]\r\n```\r\n\r\nYou can also dump the entire preprocessed solution file to check all the imports for yourself (see [gist](https://gist.github.com/joric/90422e5c4729581a465a9904e4c292db)):\r\n\r\n```python\r\nwith open(__file__, 'rt') as f:\r\n    print(f.read())\r\n```\r\n\r\nThe solution driver code writes all results to the `user.out` file, so we can use it like this:\r\n\r\n* https://leetcode.com/problems/two-sum\r\n\r\n```python\r\nclass Solution:\r\n    def twoSum(self, nums: List[int], target: int) -\u003e List[int]:\r\n        from zlib import decompress\r\n        from base64 import b64decode\r\n        open('user.out', 'wb').write(decompress(b64decode('eJzdkMEVwCAIQ++dggFyEKi2zuLr/mtItZb63KAc\\\r\nkpfwuVAYFK6tCIjNPH1KncodJMuBTqWTYUGe89hNX1Kd/K2Nh1iM3mYbkMlpIaFrvvcCaVwCH+YB3FSHVu5xXDc='))),exit(0)\r\n```\r\n\r\nThere is no approved method to get all the test cases for problems in LeetCode.\r\nYou can, however, leverage the fact that LeetCode reveals the test case that causes your code to fail.\r\nThe solution above is not very reliable, because tests and environment may change, but it's pretty fast.\r\n\r\n* https://leetcode.com/discuss/feedback/4643730/a-python-solution-that-contain-malicious-payload-in-your-website\r\n\r\nYou can explore the sandbox using shell commands, e.g. (see [gist](https://gist.github.com/joric/66d5598a912ce76cbba8bacab2d350ad)):\r\n\r\n```python\r\nimport subprocess\r\nprint(subprocess.run([\"ls\", \"-la\", \"/\"]))\r\n```\r\n\r\nYou can set your own execution time using `atexit` (worked in March 2025):\r\n\r\n* https://leetcode.com/discuss/post/6269419/0ms-bug-leetcode-by-phamvietanhvietnames-tuj2/\r\n\r\n```python\r\n__import__('atexit').register(lambda: open(\"display_runtime.txt\", \"w\").write(\"0\")) # 0..2147483647\r\n```\r\n\r\nSee https://github.com/LeetCode-Feedback/LeetCode-Feedback/issues/25646 (`we have decided not to allocate development resources to fixing it at this time.`)\r\n\r\n### Minus-two-liners\r\n\r\nSome leetcode problems may be solved at the function declaration level.\r\n\r\n* https://leetcode.com/problems/search-insert-position\r\n\r\n```python\r\nclass Solution:searchInsert=bisect_left\r\n```\r\n\r\n* https://leetcode.com/problems/permutations\r\n\r\n```python\r\nclass Solution:permute=permutations\r\n```\r\n\r\n* https://leetcode.com/problems/sort-an-array\r\n\r\n```python\r\nclass Solution:sortArray=sorted\r\n```\r\n\r\n* https://leetcode.com/problems/bulb-switcher\r\n\r\n```python\r\nclass Solution:bulbSwitch=isqrt\r\n```\r\n\r\n* https://leetcode.com/problems/search-in-rotated-sorted-array-ii\r\n\r\n```python\r\nclass Solution:search=contains\r\n```\r\n\r\n* https://leetcode.com/problems/powx-n\r\n\r\n```python\r\nclass Solution:myPow=pow\r\n```\r\n\r\nNote that it only works for the built-in functions, they can omit `self` parameter.\r\nIt's a built-in CPython feature:\r\n\r\n* https://stackoverflow.com/questions/10729909/convert-builtin-function-type-to-method-type-in-python-3\r\n\r\nYou cannot use your own function like that, without skipping the first argument.\r\n\r\n* https://leetcode.com/problems/reverse-words-in-a-string-iii\r\n\r\n```python\r\nclass Solution:reverseWords=lambda _,s:' '.join(w[::-1]for w in s.split())\r\n```\r\n\r\nIt's not necessarily shorter, because lambdas can't use semicolons.\r\n\r\nIn some cases you don't even have to write \"class Solution:\", e.g:\r\n\r\n* https://leetcode.com/problems/serialize-and-deserialize-binary-tree\r\n\r\n```python\r\nCodec=TreeNode\r\n```\r\n\r\n### Shortest\r\n\r\nLet's consider function declaration is zero lines. \r\n\r\n* https://leetcode.com/problems/account-balance-after-rounded-purchase\r\n\r\n```python\r\nclass Solution:\r\n    def accountBalanceAfterPurchase(self, x: int) -\u003e int:\r\n        return(104-x)//10*10\r\n```\r\n\r\n* https://leetcode.com/problems/majority-element\r\n\r\n```python\r\nclass Solution:\r\n    def majorityElement(self, n: List[int]) -\u003e int:\r\n        return mode(n)\r\n```\r\n\r\n* https://leetcode.com/problems/count-of-matches-in-tournament\r\n\r\n```python\r\nclass Solution:\r\n    def numberOfMatches(self, n: int) -\u003e int:\r\n        return~-n\r\n```\r\n\r\n* https://leetcode.com/problems/stone-game\r\n\r\n```python\r\nclass Solution:\r\n    def stoneGame(self, piles: List[int]) -\u003e bool:\r\n        return 1\r\n```\r\n\r\nYou can also write:\r\n\r\n```python\r\nclass Solution:stoneGame=truth\r\n```\r\n\r\n\r\n* https://leetcode.com/problems/strictly-palindromic-number\r\n\r\n```python\r\nclass Solution:\r\n    def isStrictlyPalindromic(self, n: int) -\u003e bool:\r\n        0\r\n```\r\n\r\nThis is 1-symbol solution. Notice no return operator here, can be `pass`, as function returns None. You can also do:\r\n\r\n```python\r\nclass Solution:isStrictlyPalindromic=not_\r\n```\r\n\r\n### Lambdas\r\n\r\nFictitious (anonymous) lambdas may be nested. E.g. you can use lambdas as parameters:\r\n\r\n* `(lambda a,b,c: code)(a,b,c)` becomes `(lambda a,b,c: code)(lambda a: code, lamda b: code, lambda c: code)`\r\n\r\nYou can't unpack lambda tuples in Python 3 since [PEP 3113](https://peps.python.org/pep-3113/), however, if your lambda is flat, there is an upgrade path:\r\n\r\n* `lambda (x, y): x + y` in Python 2 becomes `lambda xy:(lambda x,y: x+y)(*xy)` in Python 3.\r\n\r\nYou can also unpack multiple tuples as `lambda xy,ab:(lambda x,y,a,b: x+y+a+b)(*(xy+ab))`.\r\n\r\n* https://leetcode.com/problems/count-vowels-permutation\r\n\r\n```python\r\nclass Solution:\r\n    def countVowelPermutation(self, n: int) -\u003e int:\r\n        return sum(reduce(lambda x,_:(lambda a,e,i,o,u:(e+i+u,a+i,e+o,i,i+o))(*x),[0]*(n-1),[1]*5))\r\n            %(10**9+7)\r\n```\r\n\r\nSometimes you can unpack tuples with starmap:\r\n\r\n* https://leetcode.com/problems/length-of-longest-fibonacci-subsequence\r\n\r\n```python\r\nclass Solution:\r\n    def lenLongestFibSubseq(self, n: List[int]) -\u003e int:\r\n        s={*n};return(0,t:=max(starmap(f:=lambda a,b,c=2:s\u0026{a+b}and f(b,a+b,c+1)or c,\r\n            combinations(n,2))))[t\u003e2]\r\n```\r\n\r\n### Generators\r\n\r\nGenerator expressions `(x for y in z)` are memory efficient since they only require memory for\r\nthe one value they yield. If you don't care about memory you can use square brackets to make it a list comprehension that automatically runs the loop.\r\nYou can also exhaust a generator using `all()`, `any()` or `sum()`, depending on the return values.\r\nYou can also save a few chars using `[*g]` syntax instead of `list(g)` where g is a generator function.\r\nGenerator length `len(list(g))` can be calculated in constant memory as `sum(1 for _ in g)`.\r\n\r\nGenerator expansion `[*g]` may use a traling comma `*g,` in the initialization section (1 character shorter).\r\n\r\n* https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray\r\n\r\n```python\r\nclass Solution:\r\n    def maxAbsoluteSum(self, a: List[int]) -\u003e int:\r\n        a=[*accumulate([0]+a)];return max(a)-min(a)\r\n\r\nclass Solution:\r\n    def maxAbsoluteSum(self, a: List[int]) -\u003e int:\r\n        a=*accumulate([0]+a),;return max(a)-min(a)\r\n```\r\n\r\n### Iterators\r\n\r\nGenerators provide an easy, built-in way to create instances of Iterators.\r\nIterators are objects that have an `__iter__` and a `__next__` method.\r\nThe `iter()` method returns an iterator for the given argument.\r\nEach access iterator advances one step.\r\nMay be useful, e.g. this solution would not work without converting a string to an iterator:\r\n\r\n* https://leetcode.com/problems/append-characters-to-string-to-make-subsequence\r\n\r\n```python\r\nclass Solution:\r\n    def appendCharacters(self, s: str, t: str) -\u003e int:\r\n        s=iter(s);return sum(c not in s for c in t)\r\n```\r\n\r\nYou can also use `iter()` to split a list into chunks. The `[iter(s)]*n` trick breaks a list into pieces of size n:\r\n\r\n* https://leetcode.com/problems/minimum-number-of-changes-to-make-binary-string-beautiful\r\n\r\n```python\r\nclass Solution:\r\n    def minChanges(self, s: str) -\u003e int:\r\n        return sum(map(ne,s[::2],s[1::2]))\r\n\r\nclass Solution:\r\n    def minChanges(self, s: str) -\u003e int:\r\n        return sum(map(ne,s:=iter(s),s))\r\n\r\nclass Solution:\r\n    def minChanges(self, s: str) -\u003e int:\r\n        return sum(map(ne,*[iter(s)]*2))\r\n```\r\n\r\n### Dictionaries\r\n\r\nStarting from python version 3.7 dictionary order is guaranteed to be insertion order.\r\n\r\n* Implementation proposal: https://mail.python.org/pipermail/python-dev/2012-December/123028.html\r\n\r\nA simple Hash Table consists of key-value pair arranged in pseudo random order based on the calculations from Hash Function.\r\nThe traditional implementation of python dict used a sparse array which had lots of unused spaces in between.\r\nThe new implementation uses a combination of dense array and sparse array,\r\nthe dense array stores the key-value pair while the sparse array stores the indices to this dense array.\r\n\r\n* Faster iteration (up to 2x faster, https://mail.python.org/pipermail/python-dev/2017-December/151283.html)\r\n* Order is maintained on iterating and converting a dictionary to other data type.\r\n* Less memory required for both usage and creation of dictionaries.\r\n\r\n### Counters\r\n\r\nCounters (`collections.Counter()`) can be updated, similar to `dict.update()`, it's much faster than a sum of counters.\r\nE.g. `c[i]+=1` is equivalent to `c.update([i])`, `c[i]-=1` is `c.update({i:-1})`.\r\nTo delete a key you can use the `.pop` method (same as `del`), it's shorter than `popitem()`.\r\n\r\nNote that `c.update({i:x})` and `setitem(c,i,c[i]+x)` behaves differently. If x is negative and count becomes `\u003c=0`, the key is removed.\r\n\r\nYou can also remove zero and negative values manually (there is an the official way, see [documentation](https://docs.python.org/3/library/collections.html#collections.Counter)):\r\n\r\n```python\r\nc = Counter({1:1,2:0,3:-1}); print(c:=+c) #{1: 1}, same as c += Counter()\r\n```\r\n\r\nSince python 3.7, as a dict subclass, Counter inherited the capability to remember insertion order.\r\n\r\n* https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal\r\n\r\n```python\r\n\r\nclass Solution:\r\n    def reductionOperations(self, n: List[int]) -\u003e int:\r\n        return sum(i*v for i,(_,v)in enumerate(sorted(Counter(n).items())))\r\n\r\nclass Solution:\r\n    def reductionOperations(self, n: List[int]) -\u003e int:\r\n        return sum(i*v for i,v in enumerate(Counter(sorted(n)).values()))\r\n\r\n```\r\n\r\nSince Python 3.10 you can use `total()` to compute sum of the counts.\r\n\r\n* https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram\r\n\r\n```python\r\nclass Solution:\r\n    def minSteps(self, s: str, t: str) -\u003e int:\r\n        return sum((Counter(s)-Counter(t)).values())\r\n\r\nclass Solution:\r\n    def minSteps(self, s: str, t: str) -\u003e int:\r\n        return(Counter(s)-Counter(t)).total()\r\n```\r\n\r\nSometimes you can replace `Counter` with `set` and `count` (and it's even faster):\r\n\r\n* https://leetcode.com/problems/construct-k-palindrome-strings\r\n\r\n```python\r\nclass Solution:\r\n    def canConstruct(self, s: str, k: int) -\u003e bool:\r\n        return sum(x\u00261 for x in Counter(s).values())\u003c=k\u003c=len(s)\r\n\r\nclass Solution:\r\n    def canConstruct(self, s: str, k: int) -\u003e bool:\r\n        return sum(1\u0026s.count(x)for x in set(s))\u003c=k\u003c=len(s)\r\n```\r\n\r\n* https://leetcode.com/problems/minimum-length-of-string-after-operations\r\n\r\n```python\r\nclass Solution:\r\n    def minimumLength(self, s: str) -\u003e int:\r\n        return sum(2-x%2 for x in Counter(s).values())\r\n\r\nclass Solution:\r\n    def minimumLength(self, s: str) -\u003e int:\r\n        return sum(2-s.count(x)%2 for x in set(s))\r\n```\r\n\r\nUnlike `dict`, python `set` does NOT maintain insertion order. There are modules that implements ordered set.\r\n\r\n* [sortedcontainers](https://pypi.org/project/sortedcontainers/) - `SortedList`, `SortedDict`, `SortedSet` (maintains sorted order).\r\n* [sortedcollections](https://pypi.org/project/sortedcollections/) - `ValueSortedDict`, `ItemSortedDict`, `OrderedDict`, `OrderedSet` ([maintains insertion order](https://www.educative.io/answers/what-is-orderedset-in-python)).\r\n\r\nYou can use `SortedList` in a bunch of problems instead of a heap.\r\n\r\n* https://leetcode.com/problems/minimize-deviation-in-array\r\n\r\n```python\r\nclass Solution:\r\n    def minimumDeviation(self, nums: List[int]) -\u003e int:\r\n        r,q = inf,[]\r\n        for a in nums:\r\n            heappush(q,a%2 and -a*2 or -a)\r\n        m = -max(q)\r\n        while len(q) == len(nums):\r\n            a = -heappop(q)\r\n            r = min(r, a - m)\r\n            if a%2==0:\r\n                m = min(m, a//2)\r\n                heappush(q, -a//2)\r\n        return r\r\n\r\nfrom sortedcontainers import SortedList\r\n\r\nclass Solution:\r\n    def minimumDeviation(self, nums: List[int]) -\u003e int:\r\n        s,r = SortedList(i*2 if i \u0026 1 else i for i in nums),inf\r\n        while True:\r\n            r = min(r,s[-1]-s[0])\r\n            if 1\u0026s[-1]: break\r\n            s.add(s.pop()//2)\r\n        return r\r\n\r\nclass Solution:\r\n    def minimumDeviation(self, a: List[int]) -\u003e int:\r\n        s,r=__import__('sortedcontainers').SortedList(i*(1+i%2)for i in a),inf;\r\n        return next(r for _ in count()if[r:=min(r,s[-1]-s[0])]and 1\u0026s[-1]or s.add(s.pop()//2))\r\n```\r\n\r\n### Walrus operator\r\n\r\nThe controversial walrus operator (`:=`) added in Python 3.8 ([PEP-572](https://peps.python.org/pep-0572/)\r\nthat made [Guido to resign](https://www.infoworld.com/article/3292936/guido-van-rossum-resigns-whats-next-for-python.html)),\r\ncan be used to define or update a variable or a function (mostly used for recursive functions).\r\n\r\nYou can define and call a recursive function in a single line with Y-combinator, e.g.:\r\n\r\n```python\r\nreturn (lambda y,x:y(y,x))(lambda f,x:1 if x==0 else x*f(f,x-1),5)\r\n```\r\n\r\nBut the walrus operator syntax is much more concise:\r\n\r\n```python\r\nreturn (f:=lambda x:1 if x==0 else x*f(x-1))(5)\r\n```\r\n\r\nMany oneliners would be impossible to do without it (or rather, very hard, with nested lambdas).\r\nSometimes you don't even need extra brackets, e.g. in `map(f:=x,y)` or `next(g,f:=x)` so it may be shorter than operators separated by semicolons.\r\n\r\n* https://leetcode.com/problems/time-needed-to-inform-all-employees\r\n\r\n```python\r\nclass Solution:\r\n    def numOfMinutes(self, n: int, h: int, m: List[int], t: List[int]) -\u003e int:\r\n        return max(map(f:=cache(lambda i:~i and t[i]+f(m[i])),m))\r\n```\r\n\r\n* https://leetcode.com/problems/guess-number-higher-or-lower\r\n\r\n```python\r\nclass Solution(object):\r\n    def guessNumber(self, n: int) -\u003e int:\r\n        l,r = 1, n\r\n        while l \u003c= r:\r\n            m = (l + r) // 2\r\n            res = guess(m)\r\n            if res == 0:\r\n                return m\r\n            elif res \u003e 0:\r\n                l = m + 1\r\n            else:\r\n                r = m - 1\r\n        return 0\r\n\r\nclass Solution:\r\n    def guessNumber(self, n: int) -\u003e int:\r\n        return (f:=lambda l,h:h if l+1==h else f(m,h) if guess(m:=(l+h)//2)\u003e0 else f(l,m))(0,n)\r\n```\r\n\r\n* https://leetcode.com/problems/reverse-integer\r\n\r\n```python\r\nclass Solution:\r\n    def reverse(self, x: int) -\u003e int:\r\n        r, x = 0, abs(x)\r\n        while x:\r\n            r = r*10 + x%10\r\n            x //= 10\r\n        return ((x\u003e0)-(x\u003c0))*min(2**31, r)\r\n\r\nclass Solution:\r\n    def reverse(self, x: int) -\u003e int:\r\n        return ((x\u003e0)-(x\u003c0))*min(2**31,(f:=lambda r,x:f(r*10 + x%10, x//10) if x else r)(0,abs(x)))\r\n```\r\n\r\n* https://leetcode.com/problems/top-k-frequent-words/discuss/573662/Python-2-lines-heap/1650650\r\n\r\n```python\r\nclass Solution:\r\n    def topKFrequent(self, words: List[str], k: int) -\u003e List[str]:\r\n        return nsmallest(k,(f:=Counter(words)).keys(),lambda x:(-f[x],x))\r\n```\r\n\r\n### Setting values\r\n\r\nYou can use `__setattr__` for dictionaries or `__setitem__` for lists (both member functions return `None`).\r\nYou can also use `setattr` or `setitem` functions from the `operator` module,\r\ne.g. `c[x]=1` is the same as `setitem(c,x,1)`.\r\n\r\n* https://leetcode.com/problems/add-one-row-to-tree/discuss/764593/Python-7-lines\r\n\r\n```python\r\nclass Solution:\r\n    def addOneRow(self, root: TreeNode, v: int, d: int, isLeft: bool = True) -\u003e TreeNode:\r\n        if d == 1:\r\n            return TreeNode(v, root if isLeft else None, root if not isLeft else None)\r\n        if not root:\r\n            return None\r\n        root.left = self.addOneRow(root.left, v, d - 1, True)\r\n        root.right = self.addOneRow(root.right, v, d - 1, False)\r\n        return root\r\n\r\nclass Solution:\r\n    def addOneRow(self, root: TreeNode, v: int, d: int, isLeft: bool = True) -\u003e TreeNode:\r\n        return TreeNode(v, root if isLeft else None, root if not isLeft else None) if d==1 else \\\r\n        setattr(root,'left', self.addOneRow(root.left, v, d - 1, True)) or \\\r\n        setattr(root,'right', self.addOneRow(root.right, v, d - 1, False)) or root if root else None\r\n```\r\n\r\n* https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/1685130/Python-Recursive-with-comments\r\n\r\n```python\r\nclass Solution(object):\r\n    def deleteMiddle(self, head):\r\n        def f(a, b):\r\n            if not b:\r\n                return a.next\r\n            a.next = f(a.next, b.next.next) if b.next else f(a.next, b.next)\r\n            return a\r\n        return f(head, head.next)\r\n\r\nclass Solution(object):\r\n    def deleteMiddle(self, head):\r\n        return (f:=lambda a,b:setattr(a,'next',f(a.next, b.next.next) if b.next\r\n            else f(a.next, b.next)) or a if b else a.next)(head, head.next)\r\n```\r\n\r\nNote that `setitem` also supports slices:\r\n\r\n* https://leetcode.com/problems/count-primes/discuss/111420/Python3-solution-using-Sieve-of-Eratosthenes-time-is-O(n)\r\n\r\n```python\r\n# TLE, too slow\r\nclass Solution:\r\n    def countPrimes(self, n):\r\n        g=range(2,n);return len(reduce(lambda r,x:r-set(range(x**2,n,x))if x in r else r,g,set(g)))\r\n\r\nclass Solution:\r\n    def countPrimes(self, n):\r\n        a = [0,0]+[1]*(n-2)\r\n        for i in range(2,int(n**0.5)+1):\r\n            if a[i]:\r\n                a[i*i:n:i] = [0]*len(a[i*i:n:i])\r\n        return sum(a)\r\n\r\nclass Solution:\r\n    def countPrimes(self, n):\r\n        return sum(reduce(lambda a,i:a[i] and setitem(a,slice(i*i,n,i),[0]*len(a[i*i:n:i])) or a,\r\n            range(2,int(n**0.5)+1), [0,0]+[1]*(n-2)))\r\n```\r\n\r\nYou can also calculate primes like this:\r\n\r\n* https://leetcode.com/problems/prime-subtraction-operation\r\n\r\n```python\r\nclass Solution:\r\n    def primeSubOperation(self, a: List[int]) -\u003e bool:\r\n        m,p=1,[0]+[i for i in range(2,999)if all(i%j for j in range(2,i))];\\\r\n        return all(m\u003c(m:=x-p[bisect_right(p,x-m)-1]+1)for x in a)\r\n```\r\n\r\nNote slices can extend the list implicitly, e.g.:\r\n\r\n```python\r\na = [0,1,2]\r\na[3:4] = [3] # the result is [0,1,2,3]\r\n```\r\nBe careful though, slicing doesn't extend list beyond the slice size:\r\n\r\n```python\r\na = [0,1]\r\na[3:4] = [3,4] # the result is [0,1,3,4], NOT [0,1,?,3,4] (!)\r\n```\r\n\r\nExamples:\r\n\r\n* https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position\r\n\r\n```python\r\nclass Solution:\r\n    def longestObstacleCourseAtEachPosition(self, o: List[int]) -\u003e List[int]:\r\n        d = []\r\n        for e in o:\r\n            i = bisect_right(d,e)\r\n            if i==len(d):\r\n                d.append(0)\r\n            d[i] = e\r\n            yield i+1\r\n\r\nclass Solution:\r\n    def longestObstacleCourseAtEachPosition(self, o: List[int]) -\u003e List[int]:\r\n        d = []\r\n        for e in o:\r\n            i = bisect_right(d,e)\r\n            d[i:i+1] = [e]\r\n            yield i+1\r\n\r\nclass Solution:\r\n    def longestObstacleCourseAtEachPosition(self, o: List[int]) -\u003e List[int]:\r\n        d=[];return[setitem(d,slice(i:=bisect_right(d,e),i+1),[e])or i+1for e in o]\r\n```\r\n\r\nSometimes `exec` is shorter than `setitem`.\r\n\r\n* https://leetcode.com/problems/design-parking-system\r\n\r\n```python\r\nParkingSystem=type('',(),{'__init__':lambda s,a,b,c:setattr(s,'p',[0,a,b,c]),'addCar':lambda s,t:\\\r\n    setitem(s.p,t,s.p[t]-1)or s.p[t]\u003e=0})\r\n\r\nParkingSystem=type('',(),{'__init__':lambda s,a,b,c:setattr(s,'p',[0,a,b,c]),'addCar':lambda s,t:\\\r\n    exec('s.p[t]-=1')or s.p[t]\u003e=0})\r\n```\r\n\r\n### Classes\r\n\r\nYou can write a class or a subclass implementation in one line.\r\n\r\n* https://leetcode.com/problems/design-hashset\r\n\r\n```python\r\nMyHashSet=type('',(set,),{'remove':set.discard,'contains':set.__contains__})\r\n```\r\n\r\n* https://leetcode.com/problems/implement-stack-using-queues\r\n\r\n```python\r\nMyStack=type('',(list,),{'push':list.append,'top':lambda s:s[-1],'empty':lambda s:not s})\r\n```\r\n\r\n* https://leetcode.com/problems/product-of-the-last-k-numbers\r\n\r\n```python\r\nProductOfNumbers=type('',(list,),{'__init__':lambda s:list.__init__(s,[1]),'add':lambda s,x:\r\ns.append(s[-1]*x)if x else s.__init__(),'getProduct':lambda s,k:s[k:]and s[-1]//s[~k]or 0})\r\n```\r\n\r\nCounter subclassing fails since Python 3.7, `type() doesn't support MRO entry resolution; use types.new_class()`.\r\n\r\nWhen you try to use `types.new_class()` it says `TypeError: .__init_subclass__() takes no keyword arguments')`.\r\n\r\nThis can be avoided by creating the class first, then adding the methods to it separately, e.g.:\r\n\r\n* https://leetcode.com/problems/insert-delete-getrandom-o1\r\n\r\n```python\r\nс=Counter;с.insert=lambda s,x:s.update({x})or s[x]\u003c2;с.remove=lambda s,x:s.pop(x,0);\r\nс.getRandom=lambda s:choice([*s]);RandomizedSet=с\r\n```\r\n\r\nSometimes (not always) you can skip `__init__` and use static attributes.\r\n\r\n* https://leetcode.com/problems/design-underground-system\r\n\r\n```python\r\nUndergroundSystem=type('',(),{'h':{},'m':{},'checkIn':lambda s,i,v,t:setitem(s.m,i,(v,t)),\r\n    'checkOut':lambda s,i,d,w:(v:=s.m[i][0])and setitem(s.h,(v,d),[*map(sum,zip(s.h.pop((v,d),\r\n    (0,0)),(w-s.m[i][1],1)))]),'getAverageTime':lambda s,v,d:truediv(*s.h[v,d])})\r\n```\r\n\r\n### Bisect\r\n\r\nBinary search can be replaced by the built-in `bisect` methods.\r\nCustom binary search can use either an item getter object or a key function (since Python 3.10).\r\nStock bisect implementation is in [bisect.py](https://github.com/python/cpython/blob/main/Lib/bisect.py) (you have to know it well).\r\n\r\n* https://leetcode.com/problems/guess-number-higher-or-lower\r\n\r\n```python\r\n\r\nclass Solution:\r\n    def guessNumber(self, n: int) -\u003e int:\r\n        l,r = 1, n\r\n        while l \u003c= r:\r\n            m = (l + r) // 2\r\n            res = guess(m)\r\n            if res == 0:\r\n                return m\r\n            elif res \u003e 0:\r\n                l = m + 1\r\n            else:\r\n                r = m - 1\r\n        return 0\r\n\r\nclass Solution:\r\n    def guessNumber(self, n: int) -\u003e int:\r\n        return bisect_left(type('',(),{'__getitem__':lambda _,i: -guess(i)})(), 0, 1, n)\r\n\r\nclass Solution:\r\n    def guessNumber(self, n: int) -\u003e int:\r\n        return bisect_left(range(n), 0, key=lambda num: -guess(num))\r\n```\r\n\r\nNote that built-in methods don't support negative left margin, so you have to subtract it from the result:\r\n\r\n* https://leetcode.com/problems/kth-smallest-product-of-two-sorted-arrays.py\r\n\r\n```python\r\nclass Solution:\r\n    def kthSmallestProduct(self, a: List[int], b: List[int], k: int) -\u003e int:\r\n        f=lambda x:sum(bisect_right(b,x//y)if y\u003e0 else len(b)-bisect_left(b,ceil(x/y))if y\u003c0 else\r\n            (x\u003e=0)*len(b)for y in a)\r\n        l,r = -10**10-1, 10**10+1\r\n        while l \u003c r:\r\n            m = (l + r)//2\r\n            if f(m) \u003e= k:\r\n                r = m\r\n            else:\r\n                l = m + 1\r\n        return l\r\n\r\nclass Solution:\r\n    def kthSmallestProduct(self, a: List[int], b: List[int], k: int) -\u003e int:\r\n        f=lambda x:sum(bisect_right(b,x//y)if y\u003e0 else len(b)-bisect_left(b,ceil(x/y))if y\u003c0 else\r\n            (x\u003e=0)*len(b)for y in a)\r\n        return bisect_left(range(2*(r:=10**10)),k,key=lambda i:f(i-r))-r\r\n\r\n```\r\n\r\n### Range\r\n\r\nRange in Python 3 supports random access, so you can save a few chars using a long hardcoded range.\r\n\r\n* https://leetcode.com/problems/minimum-time-to-repair-cars/\r\n\r\n```python\r\nclass Solution:\r\n    def repairCars(self, r: List[int], c: int) -\u003e int:\r\n        return bisect_left(range(c*c*min(r)),c,key=lambda m:sum(isqrt(m//x)for x in r))\r\n\r\nclass Solution:\r\n    def repairCars(self, r: List[int], c: int) -\u003e int:\r\n        return bisect_left(range(1\u003c\u003c47),c,key=lambda m:sum(isqrt(m//x)for x in r))\r\n```\r\n\r\n### While loops\r\n\r\nWhile loops are not very oneliner-friendly. You can use `next()` function with an endless `count()` generator.\r\nNote that the default parameter runs first so you can use it for the startup code (it's not recalculated in the end).\r\n\r\n* https://leetcode.com/problems/two-sum\r\n\r\n```python\r\nclass Solution:\r\n    def twoSum(self, nums: List[int], target: int) -\u003e List[int]:\r\n        seen = {}\r\n        for i,x in enumerate(nums):\r\n            if target-x in seen:\r\n                return seen[target-x], i\r\n            seen[x] = i\r\n        return False\r\n\r\nclass Solution:\r\n    def twoSum(self, n: List[int], t: int) -\u003e List[int]:\r\n        return next(((m[t-x],i)for i,x in enumerate(n)if t-x in m or setitem(m,x,i)),m:={})\r\n```\r\n\r\n* https://leetcode.com/problems/break-a-palindrome/discuss/1481905/Python-3-one-line\r\n\r\n```python\r\nclass Solution:\r\n    def breakPalindrome(self, s: str) -\u003e str:\r\n        for i in range(len(s) // 2):\r\n            if s[i] != 'a':\r\n                return s[:i] + 'a' + s[i + 1:]\r\n        return s[:-1] + 'b' if s[:-1] else ''\r\n\r\nclass Solution:\r\n    def breakPalindrome(self, s: str) -\u003e str:\r\n        return next((s[:i]+'a'+s[i+1:]for i in range(len(s)//2)if s[i]!='a'),s[:-1]and s[:-1]+'b')\r\n```\r\n* https://leetcode.com/problems/construct-target-array-with-multiple-sums\r\n\r\n```python\r\nclass Solution:\r\n    def isPossible(self, target: List[int]) -\u003e bool:\r\n        s = sum(target)\r\n        q = [-a for a in target]\r\n        heapify(q)\r\n        while True:\r\n            x = -heappop(q)\r\n            if x==1:\r\n                return True\r\n            if s==x:\r\n                return False\r\n            d = 1 + (x-1) % (s-x)\r\n            if x==d:\r\n                return False\r\n            s = s - x + d\r\n            heappush(q, -d)\r\n\r\nclass Solution:\r\n    def isPossible(self, target: List[int]) -\u003e bool:\r\n        return (s:=sum(target),q:=[-a for a in target],heapify(q)) and next((x==1 for _ in count()\r\n        if (x:=-heappop(q))==1 or s==x or (d:=1+(x-1)%(s-x))==x or not (s:=s-x+d,heappush(q,-d))),1)\r\n```\r\n\r\nYou can also use `takewhile()`, it's also a generator, so you need to expand it (e.g. with `repeat(0)`).\r\n\r\n* https://leetcode.com/problems/sliding-window-maximum\r\n\r\n```python\r\nclass Solution:\r\n    def maxSlidingWindow(self, nums: List[int], k: int) -\u003e List[int]:\r\n        r, d = [], deque()\r\n        for i, n in enumerate(nums):\r\n            while d and n\u003e=nums[d[-1]]:\r\n                d.pop()\r\n            d.append(i)\r\n            if d[0] == i-k:\r\n                d.popleft()\r\n            r.append(nums[d[0]])\r\n        return r[k-1:]\r\n\r\nclass Solution:\r\n    def maxSlidingWindow(self, nums: List[int], k: int) -\u003e List[int]:\r\n        return (d:=deque()) or reduce(lambda r,p:(\r\n            any(takewhile(lambda _:d and p[1]\u003e=nums[d[-1]] and d.pop(), repeat(0))),\r\n            d.append(p[0]), d[0]==p[0]-k and d.popleft(), r.append(nums[d[0]])) and r,\r\n            enumerate(nums), [])[k-1:]\r\n\r\n```\r\n\r\nYou could also try `any()` or `all()` as a while loop instead of `next()`, it may be shorter.\r\nYou can assure that expression never returns `None`, using `[]` (`[None]` evaluates to `True`).\r\n\r\n* https://leetcode.com/problems/last-stone-weight\r\n\r\n```python\r\n\r\nclass Solution:\r\n    def lastStoneWeight(self, stones: List[int]) -\u003e int:\r\n        stones.sort()\r\n        while len(stones) \u003e 1:\r\n            insort(stones,stones.pop() - stones.pop())\r\n        return stones[0]\r\n\r\nclass Solution:\r\n    def lastStoneWeight(self, s: List[int]) -\u003e int:\r\n        return next((s[0] for _ in count() if not s[1:] or insort(s,s.pop()-s.pop())),s.sort())\r\n\r\nclass Solution:\r\n    def lastStoneWeight(self, s: List[int]) -\u003e int:\r\n        return (s.sort(),all(s[1:] and [insort(s,s.pop()-s.pop())] for _ in count()),s[0])[2]\r\n```\r\n\r\nYou can also evalulate multiline code with `exec`. Unlike `eval`, is not limited to a single string.\r\n\r\n* https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero\r\n\r\n```python\r\nclass Solution:\r\n    def minimumOneBitOperations(self, n: int) -\u003e int:\r\n        return next((r for _ in count()if not(n and(r:=r^n,n:=n//2))),r:=0)\r\n\r\nclass Solution:\r\n    def minimumOneBitOperations(self, n: int) -\u003e int:\r\n        r=[0];exec('while n:\\n r[0]^=n\\n n//=2');return r[0]\r\n\r\nclass Solution:\r\n    def minimumOneBitOperations(self, n: int) -\u003e int:\r\n        return(f:=lambda n:n and n^f(n//2))(n)\r\n```\r\n\r\n### Swapping values\r\n\r\nTo swap values you can use either `exec` (inline version of `a,b=b,a`) or a temporary variable (`t:=a,a:=b,b:=t`).\r\n\r\nNote that `eval` accepts only a single expression, and returns the value of the given expression,\r\nwhereas `exec` ignores the return value from its code, and always returns `None`, its use has no effect\r\non the compiled bytecode of the function where it is used. It does however affect existing variables.\r\n\r\nExample:\r\n\r\n* https://leetcode.com/problems/sort-colors\r\n\r\n```python\r\nclass Solution:\r\n    def sortColors(self, nums: List[int]) -\u003e None:\r\n        def fn(t,b):\r\n            red, white, blue = t\r\n            return (swap:=lambda a,x,y:exec('a[x],a[y]=a[y],a[x]'),(swap(nums,red,white),\r\n            (red+1,white+1,blue))[1] if nums[white]==0 else ((red,white+1,blue) if nums[white]==1\r\n            else (swap(nums,white,blue),(red,white,blue-1))[1]))[1]\r\n        reduce(fn, nums, [0,0,len(nums)-1])\r\n\r\nclass Solution:\r\n    def sortColors(self, nums: List[int]) -\u003e None:\r\n        (s:=lambda a,x,y:(t:=a[x],setitem(a,x,a[y]),setitem(a,y,t),a)[3],\r\n        f:=lambda a,i,j,k:(f(s(a,i,j),i+1,j+1,k) if a[j]==0 else f(a,i,j+1,k) if a[j]==1\r\n        else f(s(a,j,k),i,j,k-1)) if i\u003c=j\u003c=k else None)[1](nums,0,0,len(nums)-1)\r\n```\r\n\r\nAlso you can try a swap function here (but it's pretty long, I don't use it):\r\n\r\n* https://stackoverflow.com/questions/4362153/lambda-returns-lambda-in-python\r\n\r\n```python\r\nswap = lambda a,x,y:(lambda f=a.__setitem__:(f(x,(a[x],a[y])),f(y,a[x][0]),f(x,a[x][1])))()\r\n```\r\n\r\n### Map\r\n\r\nYou can use `map` for a lot of things, for example to traverse through adjacent cells.\r\n\r\n* https://leetcode.com/problems/max-area-of-island\r\n\r\n```python\r\nclass Solution:\r\n    def maxAreaOfIsland(self, grid: List[List[int]]) -\u003e int:\r\n        def dfs(i,j):\r\n            if 0\u003c=i\u003clen(grid) and 0\u003c=j\u003clen(grid[0]) and grid[i][j]:\r\n                grid[i][j] = 0\r\n                return 1 + sum(map(dfs,(i+1,i,i-1,i),(j,j+1,j,j-1)))\r\n            return 0\r\n        return max(dfs(i,j) for i in range(len(grid)) for j in range(len(grid[0])))\r\n\r\nclass Solution:\r\n    def maxAreaOfIsland(self, g: List[List[int]]) -\u003e int:\r\n        return max((f:=lambda i,j:setitem(g[i],j,0) or 1 + sum(map(f,(i+1,i,i-1,i),(j,j+1,j,j-1)))\r\n            if 0\u003c=i\u003clen(g) and 0\u003c=j\u003clen(g[0]) and g[i][j] else 0)(i,j)\r\n            for i in range(len(g)) for j in range(len(g[0])))\r\n```\r\n\r\nThough it's shorter to use complex numbers for 2d maps (introduced by Stephan Pochmann):\r\n\r\n* https://leetcode.com/problems/max-area-of-island/discuss/108565/4-lines\r\n\r\n```python\r\nclass Solution:\r\n    def maxAreaOfIsland(self, grid):\r\n        grid = {i + j*1j: val for i, row in enumerate(grid) for j, val in enumerate(row)}\r\n        def area(z):\r\n            return grid.pop(z, 0) and 1 + sum(area(z + 1j**k) for k in range(4))\r\n        return max(map(area, set(grid)))\r\n\r\nclass Solution:\r\n    def maxAreaOfIsland(self, grid):\r\n        return max(map(a:=lambda z: g.pop(z, 0) and 1 + sum(a(z + 1j**k) for k in range(4)),\r\n            set(g:= {i + j*1j: val for i, row in enumerate(grid) for j, val in enumerate(row)})))\r\n```\r\n\r\nComplex numbers in general are very useful as 2d coordinates:\r\n\r\n* https://leetcode.com/problems/path-crossing\r\n\r\n```python\r\nclass Solution:\r\n    def isPathCrossing(self, p: str) -\u003e bool:\r\n        z=0;return len(p)\u003e=len({0,*{z:=z+1j**'NESW'.find(c)for c in p}})\r\n```\r\n\r\n\r\nYou can convert lists or tuples to `True` with `!=0` instead of `bool()` (3 chars shorter).\r\n\r\n* https://leetcode.com/problems/number-of-islands\r\n\r\n```python\r\nclass Solution:\r\n    def numIslands(self, grid: List[List[str]]) -\u003e int:\r\n        grid = {i + j*1j:int(val) for i,row in enumerate(grid) for j,val in enumerate(row)}\r\n        def f(z):\r\n            return grid.pop(z,0) and bool([f(z + 1j**k) for k in range(4)])\r\n        return sum(map(f, set(grid)))\r\n\r\nclass Solution:\r\n    def numIslands(self, grid: List[List[str]]) -\u003e int:\r\n        return sum(map(f:=lambda z:g.pop(z,0) and [f(z + 1j**k) for k in range(4)]!=0,\r\n            set(g:={i + j*1j:int(x) for i,row in enumerate(grid) for j,x in enumerate(row)})))\r\n```\r\n\r\n* https://leetcode.com/problems/number-of-closed-islands\r\n\r\n```python\r\nclass Solution:\r\n    def closedIsland(self, grid: List[List[str]]) -\u003e int:\r\n        g = {i+j*1j:1-x for i,r in enumerate(grid) for j,x in enumerate(r)}\r\n        f = lambda z:g.pop(z,0) and [f(z+1j**k) for k in range(4)]!=0\r\n        sum(f(z) for z in set(g) if not(0\u003cz.real\u003clen(grid)-1 and 0\u003cz.imag\u003clen(grid[0])-1))\r\n        return sum(map(f,set(g)))\r\n\r\nclass Solution:\r\n    def closedIsland(self, grid: List[List[str]]) -\u003e int:\r\n        return (g:={i+j*1j:1-x for i,r in enumerate(grid) for j,x in enumerate(r)},\r\n            f:=lambda z:g.pop(z,0) and [f(z+1j**k) for k in range(4)]!=0,[f(z) for z in set(g)\r\n            if not(0\u003cz.real\u003clen(grid)-1 and 0\u003cz.imag\u003clen(grid[0])-1)]) and sum(map(f,set(g)))\r\n```\r\n\r\n* https://leetcode.com/problems/unique-paths-iii\r\n\r\n```python\r\nclass Solution:\r\n    def uniquePathsIII(self, grid: List[List[int]]) -\u003e int:\r\n        def f(z,r):\r\n            if x:=g.pop(z,0):\r\n                if x==3 and not g:\r\n                    r = r + 1\r\n                for k in range(4):\r\n                    r = f(z + 1j**k, r)\r\n                g.update({z:x})\r\n            return r\r\n        g = {i + j*1j:x+1 for i, row in enumerate(grid) for j,x in enumerate(row) if x!=-1}\r\n        return f(next(z for z,x in g.items() if x==2),0)\r\n\r\nclass Solution:\r\n    def uniquePathsIII(self, grid: List[List[int]]) -\u003e int:\r\n        return (g:={i + j*1j:x+1 for i, row in enumerate(grid) for j,x in enumerate(row)\r\n        if x!=-1}) and (f:=lambda z,r:[(x:=g.pop(z,0)) and (x==3 and not g and (r:=r+1),\r\n        [r:=f(z + 1j**k,r) for k in range(4)],g.update({z:x}))] and r)\r\n        (next(z for z,x in g.items() if x==2), 0)\r\n\r\n```\r\n\r\n### Unicode Find\r\n\r\nUnicode find (NOT Union Find) is the greatest trick of all time to solve graph problems.\r\nThe idea is to use string replace in a Unicode space. Introduced by Stephan Pochmann.\r\n\r\n* https://leetcode.com/problems/redundant-connection/discuss/108002/Unicode-Find-(5-short-lines)\r\n\r\n```python\r\nclass Solution:\r\n    def findRedundantConnection(self, edges: List[List[int]]) -\u003e List[int]:\r\n        t = ''.join(map(chr, range(1001)))\r\n        for u,v in edges:\r\n            if t[u]==t[v]:\r\n                return [u,v]\r\n            t = t.replace(t[u],t[v])\r\n\r\nclass Solution:\r\n    def findRedundantConnection(self, e: List[List[int]]) -\u003e List[int]:\r\n        t=''.join(map(chr,range(1001)));\r\n        return next([u,v]for u,v in e if t[u]==(t:=t.replace(t[u],t[v]))[u])\r\n```\r\n\r\nAnother example:\r\n\r\n* https://leetcode.com/problems/swim-in-rising-water\r\n\r\n```python\r\n\r\nclass Solution:\r\n    def swimInWater(self, g: List[List[int]]) -\u003e int:\r\n        n = len(g)\r\n        t,r = ''.join(map(chr,range(n*n))),range(n)\r\n        for w,i,j in sorted((g[i][j],i,j)for i,j in product(r,r)):\r\n            for x,y in ((i+1,j),(i-1,j),(i,j+1),(i,j-1)):\r\n                if n\u003ey\u003e=0\u003c=x\u003cn and g[x][y]\u003c=w:\r\n                    t = t.replace(t[i*n+j],t[x*n+y])\r\n            if t[0]==t[-1]:\r\n                return w\r\n        return 0\r\n\r\nclass Solution:\r\n    def swimInWater(self, g: List[List[int]]) -\u003e int:\r\n        n=len(g);t,r=''.join(map(chr,range(n*n))),range(n);return next((w for w,i,j in\r\n        sorted((g[i][j],i,j)for i,j in product(r,r))if[t:=t.replace(t[i*n+j],t[x*n+y]) for x,y\r\n        in((i+1,j),(i-1,j),(i,j+1),(i,j-1)) if n\u003ey\u003e=0\u003c=x\u003cn and g[x][y]\u003c=w]and t[0]==t[-1]),0)\r\n\r\n```\r\n\r\nAnother example (Q4 at https://leetcode.com/contest/weekly-contest-392):\r\n\r\n```python\r\nclass Solution:\r\n    def minimumCost(self, n: int, edges: List[List[int]], query: List[List[int]]) -\u003e List[int]:\r\n        t,c = ''.join(map(chr,range(n))),{}\r\n        for u,v,w in edges:\r\n            t = t.replace(t[u],t[v])\r\n        for u,v,w in edges:\r\n            c[t[u]] = c.get(t[u],w)\u0026w\r\n        return [0 if u==v else c[t[u]] if t[u]==t[v] else -1 for u,v in query]\r\n\r\nclass Solution:\r\n    def minimumCost(self, n: int, e: List[List[int]], q: List[List[int]]) -\u003e List[int]:\r\n        t,c=''.join(map(chr,range(n))),{};all(t:=t.replace(t[u],t[v])for u,v,_ in e);\r\n        [setitem(c,t[u],c.get(t[u],w)\u0026w)for u,v,w in e];\r\n        return[u!=v and t[u]!=t[v]and-1or c[t[u]]for u,v in q]\r\n```\r\n\r\n### Cache\r\n\r\nCache decorator, `@lru_cache` or `@cache` (since Python 3.9) may be used as an inline function `cache(lambda ...)`.\r\nEssentially, a built-in memoization. Brings computation complexity from exponential to quadratic or linear, depending of the problem.\r\nDecorator source code is in [functools.py](https://github.com/python/cpython/blob/main/Lib/functools.py).\r\nYou can also implement [C++ version](https://gist.github.com/joric/ed96c06c2e5440e0cbf84b3ff78f3a12) of a cache decorator.\r\n\r\n* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2555929/python-oneliner-dfs-with-a-cache-decorator\r\n\r\n```python\r\nclass Solution:\r\n    def maxProfit(self, k: int, prices: List[int]) -\u003e int:\r\n        @cache\r\n        def dfs(i, k, sell):\r\n            return 0 if k==0 or i==len(prices) \\\r\n            else max(dfs(i+1, k-1, 0) + prices[i], dfs(i+1, k, 1)) if sell \\\r\n            else max(dfs(i+1, k, 1)-prices[i], dfs(i+1, k, sell))\r\n        return dfs(0, k, 0)\r\n\r\nclass Solution:\r\n    def maxProfit(self, k: int, prices: List[int]) -\u003e int:\r\n        return (f:=cache(lambda i,k,s:0 if k==0 or i==len(prices)\r\n            else max(f(i+1,k-s,1-s)+prices[i]*(2*s-1),f(i+1,k,s))))(0,k,0)\r\n```\r\n\r\n* https://leetcode.com/problems/coin-change\r\n\r\n```python\r\nclass Solution:\r\n    def coinChange(self, coins: List[int], amount: int) -\u003e int:\r\n        @cache\r\n        def f(n):\r\n            return min([1 + f(n-c) for c in coins]) if n\u003e0 else 0 if n==0 else inf\r\n        x = f(amount)\r\n        return x if x!=inf else -1\r\n\r\nclass Solution:\r\n    def coinChange(self, coins: List[int], amount: int) -\u003e int:\r\n        return (lambda x:x if x!=inf else -1)((f:=cache(lambda n:\r\n            min([1+f(n-c) for c in coins]) if n\u003e0 else 0 if n==0 else inf))(amount))\r\n```\r\n\r\nIt is sometimes necessary to reset cache with `cache_clear` between tests to avoid Memory Limit Exceeded error.\r\n\r\n* https://leetcode.com/problems/length-of-the-longest-subsequence-that-sums-to-target\r\n\r\n```python\r\nclass Solution:\r\n    def lengthOfLongestSubsequence(self, a: List[int], t: int) -\u003e int:\r\n        return(a.sort(),r:=(f:=cache(lambda i,b:b and -inf if b\u003c0 or i\u003c0 else\r\n            max(1+f(i-1,b-a[i]),f(i-1,b))))(len(a)-1,t),f.cache_clear())and(-1,r)[r\u003e0]\r\n```\r\n\r\nYou can also specify maxsize option as `f=lru_cache(maxsize)(lambda ...)` in case of memory issues:\r\n\r\n* https://leetcode.com/problems/shortest-common-supersequence\r\n\r\n```python\r\n\r\nclass Solution:\r\n    def shortestCommonSupersequence(self, a: str, b: str) -\u003e str:\r\n        return(f:=lru_cache(9**5)(lambda i,j:a[i:]and b[j:]and(a[i]==b[j]and a[i]+f(i+1,j+1)\r\n            or min(a[i]+f(i+1,j),b[j]+f(i,j+1),key=len))or a[i:]or b[j:]))(0,0)\r\n```\r\n\r\n### Reduce\r\n\r\nUse it to flatten a loop.\r\n\r\n* https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1006208/python-oneliner-hashmap\r\n\r\n```python\r\nclass Solution:\r\n    def lengthOfLongestSubstring(self, s):\r\n        start, res, h = 0, 0, {}\r\n        for i, c in enumerate(s):\r\n            start = max(start, h.get(c,0))\r\n            res = max(res, i - start + 1)\r\n            h[c] = i + 1\r\n        return res\r\n\r\nclass Solution:\r\n    def lengthOfLongestSubstring(self, s):\r\n        def fn(a,b):\r\n            start, res, h = a\r\n            i, c = b\r\n            start = max(start, h.get(c,0))\r\n            res = max(res, i - start + 1)\r\n            h[c] = i + 1\r\n            return start,res,h\r\n        return reduce(fn,enumerate(s),[0,0,{}])[1]\r\n\r\nclass Solution:\r\n    def lengthOfLongestSubstring(self, s):\r\n        return reduce(lambda a,b:(s:=max(a[0],a[2].get(b[1],0)),max(a[1],b[0]-s+1),\r\n            {**a[2],b[1]:b[0]+1}),enumerate(s),(0,0,{}))[1]\r\n\r\n\r\nclass Solution:\r\n    def lengthOfLongestSubstring(self, s):\r\n        return reduce(lambda a,b:(lambda t,r,h,i,c:(s:=max(t,h.get(c,0)),max(r,i-s+1),\r\n            {**h,c:i+1}))(*a,*b),enumerate(s),(0,0,{}))[1]\r\n```\r\n\r\nAnother example:\r\n\r\n* https://leetcode.com/problems/longest-valid-parentheses\r\n\r\n```python\r\nclass Solution:\r\n    def longestValidParentheses(self, s: str) -\u003e int:\r\n        def fn(a,b):\r\n            r, s = a\r\n            i, p = b\r\n            return (max(r,i-s[-2][0]), s[:-1]) if p==')' and s[-1][1]=='(' else (r, s+[(i,p)])\r\n        return reduce(fn, enumerate(s), (0,[(-1, ')')]))[0]\r\n\r\nclass Solution:\r\n    def longestValidParentheses(self, s: str) -\u003e int:\r\n        return reduce(lambda a,b:(max(a[0],b[0]-a[1][-2][0]),a[1][:-1]) if b[1]==')'\r\n            and a[1][-1][1]=='(' else (a[0],a[1]+[b]),enumerate(s),(0,[(-1,')')]))[0]\r\n```\r\n\r\n### Product\r\n\r\nThe product function from itertools is sometimes handy.\r\n\r\n* https://leetcode.com/problems/ugly-number-ii\r\n\r\n```python\r\n\r\nclass Solution:\r\n    def nthUglyNumber(self, n: int) -\u003e int:\r\n        return sorted(2**a*3**b*5**c for a in range(32)for b in range(20)for c in range(14))[n-1]\r\n\r\nclass Solution:\r\n    def nthUglyNumber(self, n: int) -\u003e int:\r\n        return sorted(2**a*3**b*5**c for a,b,c in product(*map(range,(32,20,14))))[n-1]\r\n\r\nclass Solution:\r\n    def nthUglyNumber(self, n: int) -\u003e int:\r\n        return sorted(2**a*3**b*5**c for a,b,c in product(*[range(32)]*3))[n-1]\r\n```\r\n\r\n### Combinations\r\n\r\nCan be used anywhere in place of nested loops. Example:\r\n\r\n* https://leetcode.com/problems/count-prefix-and-suffix-pairs-ii\r\n\r\n```python\r\nclass Solution:\r\n    def countPrefixSuffixPairs(self, w: List[str]) -\u003e int:\r\n        r=range(len(w))\r\n        return sum(i\u003cj and w[j].startswith(w[i])and w[j].endswith(w[i])for i in r for j in r)\r\n\r\nclass Solution:\r\n    def countPrefixSuffixPairs(self, w: List[str]) -\u003e int:\r\n        return sum(b.startswith(a)and b.endswith(a)for a,b in combinations(w,2))\r\n\r\nclass Solution:\r\n    def countPrefixSuffixPairs(self, w: List[str]) -\u003e int:\r\n        return sum(a==b[:len(a)]==b[-len(a):]for a,b in combinations(w,2))\r\n```\r\n\r\n### Semicolons\r\n\r\nNobody will stop you from using semicolons, but you'd still have to convert while and for loops.\r\n\r\nExample:\r\n\r\n* https://leetcode.com/problems/swapping-nodes-in-a-linked-list\r\n\r\n```python\r\nclass Solution:\r\n    def swapNodes(self, h: Optional[ListNode], k: int) -\u003e Optional[ListNode]:\r\n        q = h\r\n        i = 1\r\n        d = {}\r\n        while q:\r\n            d[i] = q\r\n            q = q.next\r\n            i += 1\r\n        d[k].val, d[i-k].val = d[i-k].val, d[k].val\r\n        return h\r\n\r\nclass Solution:\r\n    def swapNodes(self, h: Optional[ListNode], k: int) -\u003e Optional[ListNode]:\r\n        q=h;i=1;d={};all(q and(setitem(d,i,q),q:=q.next,i:=i+1) for _\r\n            in count());d[k].val,d[i-k].val=d[i-k].val,d[k].val;return h\r\n\r\nclass Solution:\r\n    def swapNodes(self, h: Optional[ListNode], k: int) -\u003e Optional[ListNode]:\r\n        l=[h]+[h:=h.next for _ in[1]*10**5if h];a,b=l[k-1],l[~k];a.val,b.val=b.val,a.val;return l[0]\r\n```\r\n\r\n### Math tricks\r\n\r\nMany leetcode problems use Fibonacci sequence that can be calculated using a variety of different methods.\r\n\r\n* https://leetcode.com/problems/fibonacci-number\r\n\r\n```python\r\nclass Solution:\r\n    def fib(self, n: int) -\u003e int:\r\n        a,b = 0,1\r\n        for _ in range(n):\r\n            a,b = b,a+b\r\n        return a \r\n\r\n# classic Binet, https://r-knott.surrey.ac.uk/Fibonacci/fibFormula.html\r\n\r\nclass Solution:\r\n    def fib(self, n: int) -\u003e int:\r\n        phi = (1 + sqrt(5)) / 2\r\n        return round(pow(phi, n) / sqrt(5))\r\n\r\nclass Solution:\r\n    def fib(self, n: int) -\u003e int:\r\n        n-=1;r=5**.5;return round(((1+r)/2)**-~n/r)\r\n\r\nclass Solution:\r\n    def fib(self, n: int) -\u003e int:\r\n        r=5**.5;return round(((1+r)/2)**n/r)\r\n\r\n# generating function, https://en.wikipedia.org/wiki/Generating_function\r\n\r\nclass Solution:\r\n    def fib(self, n: int) -\u003e int:\r\n        x=1\u003c\u003c32;return x**~-n*x*x//(x*x+~x)%x\r\n\r\nclass Solution:\r\n    def fib(self, n: int) -\u003e int:\r\n        x=9**n;return x**-~n//(x*x+~x)%x\r\n\r\nclass Solution:\r\n    def fib(self, n: int) -\u003e int:\r\n        return pow(x:=2\u003c\u003cn,n+1,x*x+~x)%x\r\n```\r\n\r\n* https://leetcode.com/problems/climbing-stairs\r\n\r\n\r\n```python\r\nclass Solution:\r\n    def climbStairs(self, n: int) -\u003e int:\r\n        a=b=1\r\n        for _ in range(n):\r\n            a,b = b,a+b\r\n        return a\r\n\r\nclass Solution:\r\n    def climbStairs(self, n):\r\n        return pow(x:=2\u003c\u003cn,n+2,x*x+~x)%x\r\n```\r\n\r\n* https://leetcode.com/problems/n-th-tribonacci-number\r\n\r\n```python\r\nclass Solution:\r\n    def tribonacci(self, n):\r\n        a,b,c = 1,0,0\r\n        for _ in range(n):\r\n            a,b,c = b,c,a+b+c\r\n        return c\r\n\r\n# https://mathworld.wolfram.com/TribonacciNumber.html\r\n\r\nclass Solution:\r\n    def tribonacci(self, n: int) -\u003e int:\r\n        return round((599510/325947)**n*39065/116186)\r\n\r\nclass Solution:\r\n    def tribonacci(self, n: int) -\u003e int:\r\n        return pow(x:=2\u003c\u003cn,n+2,~-x*x*x+~x)%x\r\n```\r\n\r\n### Regular expressions\r\n\r\nMany problems can be solved with a single regex:\r\n\r\n* https://leetcode.com/problems/sort-vowels-in-a-string\r\n\r\n```python\r\nclass Solution:\r\n    def sortVowels(self, s: str) -\u003e str:\r\n        return re.sub(t:='(?i)[aeiou]',lambda m,v=sorted(findall(t,s)):heappop(v),s)\r\n```\r\n\r\n* https://leetcode.com/problems/valid-word\r\n\r\n```python\r\nclass Solution:\r\n    def isValid(self, w: str) -\u003e bool:\r\n        return match('^(?=.*[aeiou])(?=.*[^0-9aeiou])[a-z0-9]{3,}$',w,I)\r\n```\r\n\r\n* https://leetcode.com/problems/make-the-string-great\r\n\r\n```python\r\nclass Solution:\r\n    def makeGood(self, s: str) -\u003e str:\r\n        [s:=re.sub(r'(.)(?!\\1)(?i:\\1)','',s)for _ in s];return s\r\n```\r\n\r\n* https://leetcode.com/problems/clear-digits\r\n\r\n```python\r\nclass Solution:\r\n    def clearDigits(self, s: str) -\u003e str:\r\n        [s:=re.sub('\\D\\d','',s)for _ in s];return s\r\n```\r\n\r\n* https://leetcode.com/problems/circular-sentence\r\n\r\n```python\r\nclass Solution:\r\n    def isCircularSentence(self, s: str) -\u003e bool:\r\n        return not re.search('(.) (?!\\\\1)',s+' '+s)\r\n```\r\n\r\n### Accumulate\r\n\r\nThere are many uses for `itertools.accumulate`, remember that it supports any function besides the default \"sum\".\r\n\r\n```python\r\nclass Solution():\r\n    def stalinSort(self, a: List[int]) -\u003e List[int]:\r\n        return [x for i,x in enumerate(a)if x\u003e=max(a[:i+1])]\r\n\r\nclass Solution():\r\n    def stalinSort(self, a: List[int]) -\u003e List[int]:\r\n        return compress(a,map(ge,a,accumulate(a,max)))\r\n```\r\n\r\n### Kadane\r\n\r\nFor the Kadane-like problems you have to maintain a couple of counters. You can just use `max` on a comprehension.\r\n\r\n* https://leetcode.com/problems/maximum-subarray\r\n\r\n```python\r\nclass Solution:\r\n    def maxSubArray(self, nums: List[int]) -\u003e int:\r\n        cur_max, max_till_now = 0, -inf\r\n        for c in nums:\r\n            cur_max = max(c, cur_max + c)\r\n            max_till_now = max(max_till_now, cur_max)\r\n        return max_till_now\r\n\r\nclass Solution:\r\n    def maxSubArray(self, n: List[int]) -\u003e int:\r\n        return max(accumulate(n,lambda c,x:max(c+x,x)))\r\n\r\nclass Solution:\r\n    def maxSubArray(self, n: List[int]) -\u003e int:\r\n        c=0;return max(c:=max(c+x,x)for x in n)\r\n```\r\n\r\nIf there are more counters, you can combine intermediary counter and target counter calculation using a walrus operator.\r\n\r\n* https://leetcode.com/problems/maximum-ascending-subarray-sum\r\n\r\n```python\r\n\r\nclass Solution:\r\n    def maxAscendingSum(self, n: List[int]) -\u003e int:\r\n        p=c=0;return max((c:=x+c*(x\u003ep),p:=x)[0]for x in n)\r\n\r\nclass Solution:\r\n    def maxAscendingSum(self, n: List[int]) -\u003e int:\r\n        p=c=0;return max(c:=x+c*(x\u003ep)+0*(p:=x)for x in n)\r\n\r\nclass Solution:\r\n    def maxAscendingSum(self, n: List[int]) -\u003e int:\r\n        p=c=0;return max(c:=x+c*(p\u003c(p:=x))for x in n)\r\n```\r\n\r\n### Asterisk operator\r\n\r\nYou can save a few characters using asterisk operator `*`.\r\nOne `*` means \"expand this as a list\", two `**` means \"expand this as a dictionary\".\r\nNote with `**` you can only expand dictionaries, e.g. `{'a':1, **dict}`.\r\n\r\n* https://leetcode.com/problems/check-if-it-is-a-straight-line\r\n\r\n```python\r\nclass Solution:\r\n    def checkStraightLine(self, p):\r\n        (a,b),(c,d)=p[:2];return all((x-a)*(d-b)==(c-a)*(y-b)for x,y in p)\r\n\r\nclass Solution:\r\n    def checkStraightLine(self, p):\r\n        (a,b),(c,d),*_=p;return all((x-a)*(d-b)==(c-a)*(y-b)for x,y in p)\r\n```\r\n\r\nThere's a nice way to convert an iterable to list, e.g. `x=[*g]` equals `*x,=g` (1 char shorter). Or expand lists:\r\n\r\n* https://leetcode.com/problems/maximum-average-subarray-i\r\n\r\n\r\n```python\r\nclass Solution:\r\n    def findMaxAverage(self, n: List[int], k: int) -\u003e float:\r\n        s=[0]+[*accumulate(n)];return max(map(sub,s[k:],s))/k\r\n\r\nclass Solution:\r\n    def findMaxAverage(self, n: List[int], k: int) -\u003e float:\r\n        s=[0,*accumulate(n)];return max(map(sub,s[k:],s))/k\r\n```\r\n\r\nYou can also use this syntax to unpack iterables, e.g. `a,*b,c=range(5)` means `a=1;b=[2,3,4];c=5`.\r\n\r\n* https://leetcode.com/problems/number-of-ways-to-split-array\r\n\r\n```python\r\nclass Solution:\r\n    def waysToSplitArray(self, a: list[int]) -\u003e int:\r\n        return sum(map((sum(a)/2).__le__,accumulate(a[:-1])))\r\n\r\nclass Solution:\r\n    def waysToSplitArray(self, a: list[int]) -\u003e int:\r\n        *p,s=accumulate(a);return sum(map((s/2).__le__,p))\r\n```\r\n\r\n### Rotations\r\n\r\nRotate array problem was published in Programming Pearls ([pages 624-625 of a September 1983 edition](https://dl.acm.org/doi/pdf/10.1145/358172.358176)).\r\n\r\n_The problem continues to look hard until you finally come\r\nup with the right aha! insight. Let's view it as transforming\r\nthe array AB into the array BA, but let's also assume we have\r\na subroutine that reverses the elements in a specified portion\r\nof the array._\r\n\r\nRotating string \"ABCDEFGH\" by i=3 characters left (n is string length, indexes start from 1):\r\n\r\n```c\r\nreverse(1, i)    /* CBADEFGH */\r\nreverse(i+1, n)  /* CBAHGFED */\r\nreverse(1, n)    /* DEFGHABC */\r\n```\r\n\r\n_This implementation of rotating a ten-element array up by\r\nfive positions ([Figure 1](https://i.imgur.com/UvQJ6tu.png)) is from Doug Mcllroy; try it.\r\nThe reversal code is time- and space-efficient, and is so\r\nshort and simple that it's pretty hard to get wrong._\r\n\r\n_It is exactly the code that Kernighan and Plauger use in the text\r\neditor in their book. Brian Kernighan reports that this code\r\nindeed ran correctly the first time it was executed, while\r\ntheir previous code for a similar task contained several bugs.\r\nThis code is also used in several text editors, including the\r\nUNIX editor ed._\r\n\r\n* https://leetcode.com/problems/rotate-array\r\n\r\n```python\r\n# rotate array AKA Doug Mcllroy, Programming Pearls\r\n# reverse parts at split point then reverse whole array\r\n# you can do it in a reverse order to change direction\r\nclass Solution:\r\n    def rotate(self, nums: List[int], k: int) -\u003e None:\r\n        def reverse(i, j):\r\n            while i \u003c j:\r\n                nums[i], nums[j] = nums[j], nums[i]\r\n                i, j = i+1, j-1\r\n        n = len(nums)\r\n        k = k % n\r\n        reverse(0, n-1)\r\n        reverse(0, k-1)\r\n        reverse(k, n-1)\r\n        return nums\r\n```\r\n\r\nIt's pretty suboptimal though. Reversing three times is simplest but moves every element exactly twice, takes O(N) time and O(1) space\r\nIt is possible to circle shift an array moving each element exactly once also in O(N) time and O(1) space\r\n(https://stackoverflow.com/questions/876293/fastest-algorithm-for-circle-shift-n-sized-array-for-m-position).\r\n\r\n```python\r\n# GCD solution, true O(n)\r\nclass Solution:\r\n    def rotate(self, nums: List[int], k: int) -\u003e None:\r\n        n = len(nums)\r\n        shift = n - (k % n)\r\n        for i in range(gcd(n, shift)):\r\n            j = i\r\n            while (k := (j + shift) % n) != i:\r\n                nums[j],nums[k] = nums[k],nums[j]\r\n                j = k\r\n```\r\n\r\nOther ways:\r\n\r\n```python\r\n# using built-in reverse function\r\nclass Solution:\r\n    def rotate(self, nums: List[int], k: int) -\u003e None:\r\n        k = k % len(nums)\r\n        nums[:k] = reversed(nums[:k])\r\n        nums[k:] = reversed(nums[k:])\r\n        nums.reverse()\r\n\r\n# not inplace\r\nclass Solution:\r\n    def rotate(self, nums: List[int], k: int) -\u003e None:\r\n        [nums.insert(0,nums.pop()) for _ in range(k)]\r\n\r\n# deque built-in rotate method\r\nclass Solution:\r\n    def rotate(self, nums: List[int], k: int) -\u003e None:\r\n        nums[:]=(q:=deque(nums)).rotate(k) or q\r\n\r\n# minified\r\nclass Solution:\r\n    def rotate(self, a: List[int], k: int) -\u003e None:\r\n        k%=len(a);a[:]=a[-k:]+a[:-k]\r\n```\r\n\r\nThere also problems where you have to determine if string was rotated. The trick is to search in a string concatenated with its copy.\r\n\r\n* https://leetcode.com/problems/repeated-substring-pattern/solutions/826417/rust-oneliner-by-joric-mmmu/\r\n\r\n_If s consists of repeating parts then at some point it should be equal to the rotated version of itself.\r\nChecking If s is a sub-string of (s+s)[1:-1] basicaly does all the job of checking for all rotated versions\r\nof s except s+s just in a single operation (which is usually SIMD-accelerated)._\r\n\r\n```python\r\nclass Solution:\r\n    def repeatedSubstringPattern(self, s: str) -\u003e bool:\r\n        return s in (s+s)[1:-1]\r\n```\r\n\r\n* https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/\r\n\r\n```python\r\nclass Solution:\r\n    def check(self, a: List[int]) -\u003e bool:\r\n        return sum(map(gt,a,a[1:]+a))\u003c2\r\n```\r\n\r\n### Itemgetter\r\n\r\nNote that `key=itemgetter(n)` is the same length as `key=lambda x:x[n]` but a little bit clearer to read.\r\nThe performance of itemgetter is also better than lambda (up to 2x, because of the creation of the lambda).\r\n\r\nSometimes you can skip `key=itemgetter(0)` in comparison operations by converting an argument\r\nto a tuple (15 characters shorter).\r\n\r\n* https://leetcode.com/problems/maximum-profit-in-job-scheduling\r\n\r\n```python\r\n\r\nclass Solution:\r\n    def jobScheduling(self, s: List[int], e: List[int], p: List[int]) -\u003e int:\r\n        a=sorted(zip(s,e,p));return(f:=cache(lambda i:i-len(a)and max(f(\r\n            bisect_left(a,a[i][1],key=itemgetter(0)))+a[i][2],f(i+1))))(0)\r\n\r\nclass Solution:\r\n    def jobScheduling(self, s: List[int], e: List[int], p: List[int]) -\u003e int:\r\n        a=sorted(zip(s,e,p));return(f:=cache(lambda i:i-len(a)and max(f(\r\n            bisect_left(a,(a[i][1],)))+a[i][2],f(i+1))))(0)\r\n\r\n```\r\n\r\n### Pop\r\n\r\nYou could also use `map(list.pop, v)` instead of `[x[-1] for x in v]` to collect the last elements of the list.\r\n\r\n* https://leetcode.com/problems/diagonal-traverse-ii\r\n\r\n```python\r\nclass Solution:\r\n    def findDiagonalOrder(self, n: List[List[int]]) -\u003e List[int]:\r\n        return map(list.pop,sorted([i+j,j,t]for i,r in enumerate(n)for j,t in enumerate(r)))\r\n```\r\n\r\n### Zip\r\n\r\nUsing `zip` to get elements from the list of tuples is usually shorter, but not always:\r\n\r\n* https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes\r\n\r\n```python\r\nclass Solution:\r\n    def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -\u003e List[int]:\r\n        return {*range(n)}-{*[*zip(*edges)][1]}\r\n\r\nclass Solution:\r\n    def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -\u003e List[int]:\r\n        return {*range(n)}-{j for _,j in edges}\r\n```\r\n\r\n### Comparison chaining\r\n\r\nPython has comparison chaining. You can use expressions like `0\u003c=i\u003cn`, `m\u003ej\u003e=0\u003c=i\u003cn` and `a!=b!=c` in a single condition.\r\n\r\n* https://leetcode.com/problems/expressive-words/discuss/122660/C%2B%2BJavaPython-2-Pointers-and-4-pointers\r\n\r\n```python\r\nclass Solution:\r\n    def expressiveWords(self, s: str, words: List[str]) -\u003e int:\r\n        def f(v,w,j=0):\r\n            for i in range(len(v)):\r\n                if j\u003clen(w) and v[i]==w[j]:\r\n                    j += 1\r\n                elif v[i-1:i+2] != v[i]*3 != v[i-2:i+1]:\r\n                    return False\r\n            return j==len(w)\r\n        return sum(f(s,w) for w in words)\r\n\r\nclass Solution:\r\n    def expressiveWords(self, s: str, words: List[str]) -\u003e int:\r\n        return sum((f:=lambda v,w,j=0:next((0 for i in range(len(v)) if not(j\u003clen(w) and v[i]==w[j]\r\n            and (j:=j+1))and v[i-1:i+2]!=v[i]*3!=v[i-2:i+1]),1) and j==len(w))(s,w) for w in words)\r\n\r\n```\r\n\r\nPython handles multi-argument comparisons in the same order as an `and` operator, so you can use a shorter form:\r\n\r\n* https://leetcode.com/problems/power-of-four\r\n\r\n```python\r\nclass Solution:\r\n    def isPowerOfFour(self, n: int) -\u003e bool:\r\n        return n\u003e0 and log(n,4)%1==0\r\n\r\nclass Solution:\r\n    def isPowerOfFour(self, n: int) -\u003e bool:\r\n        return n\u003e0==log(n,4)%1\r\n```\r\n\r\nYou can check if any of the numbers is negative as `x|y\u003c0` or if both numbers are non-zero as `x|y`.\r\n\r\n* https://leetcode.com/problems/minimum-path-sum\r\n\r\n```python\r\nclass Solution:\r\n    def minPathSum(self, grid: List[List[int]]) -\u003e int:\r\n        return (f:=cache(lambda i,j:i|j\u003c0 and inf or grid[i][j]+(i|j and min(f(i,j-1),f(i-1,j)))))\r\n            (len(grid)-1,len(grid[0])-1)\r\n```\r\n\r\nYou can use bitwise `\u0026`,`|` instead of `and`,`or` where possible. You can use `x\u00261` instead of `x==1`, if 0\u003c=x\u003c=2.\r\n\r\n* https://leetcode.com/problems/scramble-string\r\n\r\n```python\r\n\r\nclass Solution:\r\n    def isScramble(self, s1: str, s2: str) -\u003e bool:\r\n        return (f:=cache(lambda a,b:a==b or any((f(a[:i],b[:i]) and f(a[i:],b[i:]))\r\n            or (f(a[i:],b[:-i]) and f(a[:i],b[-i:])) for i in range(1,len(a)))))(s1,s2)\r\n\r\nclass Solution:\r\n    def isScramble(self, s1: str, s2: str) -\u003e bool:\r\n        return (f:=cache(lambda a,b:a==b or any((f(a[:i],b[:i])\u0026f(a[i:],b[i:]))\r\n            |(f(a[i:],b[:-i])\u0026f(a[:i],b[-i:])) for i in range(1,len(a)))))(s1,s2)\r\n```\r\n\r\n### Bitwise inversion\r\n\r\n`~` reverts every bit. Therefore, `~x` means `-x-1`. You can use it as reversed index, i.e. for `i=0`, `a[~i]` means `a[-1]`, etc. or just replace `-x-1` with `~x`.\r\n\r\nFor integer n, you can write `n+1` as `-~n`, `n-1` as `~-n`. This uses the same number of characters, but can indirectly cut spaces or parens for operator precedence.\r\n\r\n\r\n* https://leetcode.com/problems/spiral-matrix-ii/\r\n\r\n```python\r\nclass Solution:\r\n    def generateMatrix(self, n: int) -\u003e List[List[int]]:\r\n        r=range(n);return[[4*(n-(a:=min(min(i,n-i-1),min(j,n-j-1))))\r\n            *a+(i+j-2*a+1,4*(n-2*a-1)-(i+j-2*a)+1)[i\u003ej] for j in r] for i in r]\r\n\r\nclass Solution:\r\n    def generateMatrix(self, n: int) -\u003e List[List[int]]:\r\n        r=range(n);return[[4*(n-(a:=min(i,j,~i+n,~j+n)))\r\n            *a+(i+j-2*a+1,4*n-6*a-i-j-3)[i\u003ej]for j in r]for i in r]\r\n```\r\n\r\n### If-Else\r\n\r\nYou can replace `0 if x==y else z` with `x-y and z`, it's a little bit counterintuitive, but shorter.\r\n\r\nCondition `x if c else y` can be written as `c and x or y`, it's shorter but depends on x (x should not be 0).\r\n\r\n* https://leetcode.com/problems/snakes-and-ladders/discuss/173378/Diagram-and-BFS\r\n\r\n```python\r\nclass Solution:\r\n    def snakesAndLadders(self, board: List[List[int]]) -\u003e int:\r\n        n,v,q = len(board),{1:0},[1]\r\n        def f(i):\r\n            x = (i - 1)%n\r\n            y = (i - 1)//n\r\n            c = board[~y][~x if y%2 else x]\r\n            return c if c\u003e0 else i\r\n        for i in q:\r\n            for j in range(i+1, i+7):\r\n                k = f(j)\r\n                if k==n*n:\r\n                    return v[i]+1\r\n                if k not in v:\r\n                    v[k] = v[i]+1\r\n                    q.append(k)\r\n        return -1\r\n\r\nclass Solution:\r\n    def snakesAndLadders(self, board: List[List[int]]) -\u003e int:\r\n        return (n:=len(board),v:={1:0},q:=[1]) and next((v[i]+1 for i in q for j in range(i+1,i+7)\r\n            if (k:=(x:=(j-1)%n,y:=(j-1)//n) and ((c:=board[~y][y%2 and ~x or x])\u003e0 and c or j))==n*n\r\n            or (k not in v and (v.update({k:v[i]+1}) or q.append(k)))),-1)\r\n```\r\n\r\n### Boolean\r\n\r\nYou can use booleans as indices in lists, even nested: `(a,(b,c)[u==w])[x==y]`, or you can multiply by a boolean.\r\n\r\n* https://leetcode.com/problems/removing-stars-from-a-string\r\n\r\n```python\r\nclass Solution:\r\n    def removeStars(self, s: str) -\u003e str:\r\n        return reduce(lambda r,c:(r[:-1],r+c)[c\u003e'*'],s)\r\n```\r\n\r\n* https://leetcode.com/problems/simplify-path\r\n\r\n```python\r\nclass Solution:\r\n  def simplifyPath(self, path: str) -\u003e str:\r\n    return'/'+'/'.join(reduce(lambda r,p:(r+[p]*('.'!=p!=''),r[:-1])[p=='..'],path.split('/'),[]))\r\n```\r\n\r\n### Cmp\r\n\r\nPython 3 lacks `cmp` (3-way compare) and sign function (`copysign(bool(x),x)` is too long), but you can use `(x\u003e0)-(x\u003c0)` for `sign(x)`\r\nand `(a\u003eb)-(a\u003cb)` for `cmp(a,b)`. Note you can use `-1,0,1` indexes for Python lists natively.\r\n\r\n* https://leetcode.com/problems/stone-game-iii\r\n\r\n```python\r\nclass Solution:\r\n    def stoneGameIII(self, v: List[int]) -\u003e str:\r\n        f=cache(lambda i:i\u003clen(v)and max(sum(v[i:i+k])-f(i+k)for k in(1,2,3)));x=f(0);\r\n        return('Tie','Alice','Bob')[(x\u003e0)-(x\u003c0)]\r\n        # return(('Tie','Bob')[x\u003c0],'Alice')[x\u003e0] # or like this (1 char shorter)\r\n```\r\n\r\nYou can replace `cmp` written as `lambda x:(x\u003e0)-(x\u003c0)` with `0..__le__` or `.0.__le__` (11 characters shorter).\r\n\r\n* https://leetcode.com/problems/rearrange-array-elements-by-sign\r\n\r\n```python\r\nclass Solution:\r\n    def rearrangeArray(self, n: List[int]) -\u003e List[int]:\r\n        n.sort(key=lambda x:(x\u003e0)-(x\u003c0));return chain(*zip(n[len(n)//2:],n))\r\n\r\nclass Solution:\r\n    def rearrangeArray(self, n: List[int]) -\u003e List[int]:\r\n        n.sort(key=0..__le__);return chain(*zip(n[len(n)//2:],n)) \r\n\r\n```\r\n\r\nYou can replace `x\u003e0` predicate with `0..__lt___` function and replace `x!=0` with `operator.truth` or just `bool`:\r\n\r\n* https://leetcode.com/problems/merge-nodes-in-between-zeros\r\n\r\n```python\r\nclass Solution:\r\n    def mergeNodes(self, h: Optional[ListNode]) -\u003e Optional[ListNode]:\r\n        return h.deserialize(str([sum(v)for k,v in groupby(eval(h.serialize(h)),bool)if k]))\r\n```\r\n\r\nCmp as a sorting key may be reduced further to a tuple `(x\u003ep,x==p)`.\r\n\r\n* https://leetcode.com/problems/partition-array-according-to-given-pivot\r\n\r\n```python\r\nclass Solution:\r\n    def pivotArray(self, a: List[int], p: int) -\u003e List[int]:\r\n        return sorted(a,key=lambda x:(x\u003ep,x==p))\r\n```\r\n\r\n### Mode\r\n\r\nQuite a few things become shorter with `statistics.mode` (most common value of discrete or nominal data).\r\n\r\n* https://leetcode.com/problems/find-missing-and-repeated-values\r\n\r\n```python\r\nclass Solution:\r\n    def findMissingAndRepeatedValues(self, g: List[List[int]]) -\u003e List[int]:\r\n        return sum(a:=sum(g,[]))-sum({*a}),(n:=len(a))*(n+1)//2-sum({*a})\r\n\r\nclass Solution:\r\n    def findMissingAndRepeatedValues(self, g: List[List[int]]) -\u003e List[int]:\r\n        return mode(a:=sum(g,[])),comb(len(a)+1,2)-sum({*a})\r\n```\r\n\r\n* https://leetcode.com/problems/set-mismatch\r\n\r\n```python\r\nclass Solution:\r\n    def findErrorNums(self, nums: List[int]) -\u003e List[int]:\r\n        t=sum({*nums});return sum(nums)-t,comb(len(nums)+1,2)-t\r\n\r\nclass Solution:\r\n    def findErrorNums(self, nums: List[int]) -\u003e List[int]:\r\n        return mode(nums),comb(len(nums)+1,2)-sum({*nums})\r\n```\r\n\r\n* https://leetcode.com/problems/majority-element\r\n\r\n```python\r\nclass Solution:\r\n    def majorityElement(self, nums: List[int]) -\u003e int:\r\n        return sorted(nums)[len(nums)//2]\r\n\r\nclass Solution:\r\n    def majorityElement(self, nums: List[int]) -\u003e int:\r\n        return mode(nums)\r\n```\r\n\r\n* https://leetcode.com/problems/find-the-duplicate-number\r\n\r\n```python\r\n# https://youtu.be/pKO9UjSeLew (Joma Tech: If Programming Was An Anime)\r\nclass Solution:\r\n    def findDuplicate(self, nums: List[int]) -\u003e int:\r\n        tortoise = hare = nums[0]\r\n        while True:\r\n            tortoise = nums[tortoise]\r\n            hare = nums[nums[hare]]\r\n            if tortoise == hare:\r\n                break\r\n        tortoise = nums[0]\r\n        while tortoise != hare:\r\n            tortoise = nums[tortoise]\r\n            hare = nums[hare]\r\n        return hare\r\n\r\nclass Solution:\r\n    def findDuplicate(self, nums: List[int]) -\u003e int:\r\n        return mode(nums)\r\n```\r\n\r\n### Encode\r\n\r\nYou can use `s.encode()` instead of `ord` or `map(ord,s)` It's the same length but doesn't need generation evaluation.\r\n\r\n* https://leetcode.com/problems/score-of-a-string\r\n\r\n```python\r\nclass Solution:\r\n    def scoreOfString(self, s: str) -\u003e int:\r\n        return sum(abs(x-y)for x,y in pairwise(map(ord,s)))\r\n\r\nclass Solution:\r\n    def scoreOfString(self, s: str) -\u003e int:\r\n        return sum(map(abs,map(sub,s:=s.encode(),s[1:])))\r\n```\r\n\r\n### Enumerate\r\n\r\nYou can use `count()` and `map` to replace an `enumerate` list comprehension (a few characters shorter):\r\n\r\n* https://leetcode.com/problems/maximum-total-importance-of-roads\r\n\r\n```python\r\nclass Solution:\r\n    def maximumImportance(self, n: int, r: List[List[int]]) -\u003e int:\r\n        return sum(v*(n-i)for i,(_,v)in enumerate(Counter(chain(*r)).most_common()))\r\n\r\nclass Solution:\r\n    def maximumImportance(self, n: int, r: List[List[int]]) -\u003e int:\r\n        return-sum(map(mul,count(-n),sorted(Counter(chain(*r)).values())[::-1]))\r\n```\r\n\r\n### Starmap\r\n\r\nStarmap makes an iterator that computes the function using arguments obtained from the iterable.\r\nUsed instead of map() when argument parameters have already been \"pre-zipped\" into tuples (see [itertools.starmap](https://docs.python.org/3/library/itertools.html#itertools.starmap)).\r\n\r\nApplying a function to an iterable with `starmap` and `pairwise` may be done with `map` (12 chars shorter):\r\n\r\n* https://leetcode.com/problems/find-the-original-array-of-prefix-xor\r\n\r\n```python\r\nclass Solution:\r\n    def findArray(self, p: List[int]) -\u003e List[int]:\r\n        return starmap(xor,pairwise([0]+p))\r\n\r\nclass Solution:\r\n    def findArray(self, p: List[int]) -\u003e List[int]:\r\n        return map(xor,p,[0]+p)\r\n```\r\n\r\nVery often you can replace `zip` with `map`, it evaluates iterables the same way:\r\n\r\n* https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone[\r\n\r\n```python\r\nclass Solution:\r\n    def minMovesToSeat(self, s: List[int], t: List[int]) -\u003e int:\r\n        return sum(abs(a-b)for a,b in zip(*map(sorted,(s,t))))\r\n\r\nclass Solution:\r\n    def minMovesToSeat(self, s: List[int], t: List[int]) -\u003e int:\r\n        return sum(map(abs,map(sub,*map(sorted,(s,t)))))\r\n```\r\n\r\nYou can also replace `starmap` and `enumerate` with `map` and `count()` (7 characters shorter).\r\n\r\n* https://leetcode.com/problems/count-number-of-bad-pairs\r\n\r\n```python\r\nclass Solution:\r\n    def countBadPairs(self, a: List[int]) -\u003e int:\r\n        return sum(x*(len(a)-x)for x in Counter(starmap(sub,enumerate(a))).values())//2\r\n\r\nclass Solution:\r\n    def countBadPairs(self, a: List[int]) -\u003e int:\r\n        return sum(x*(len(a)-x)for x in Counter(map(sub,a,count())).values())//2\r\n\r\n```\r\n\r\n### Comb\r\n\r\nYou can write combination function (binomial) `n*(n-1)//2` as `comb(n,2)`, or replace `(n-1)` with `~-n` to cut parens.\r\n\r\n* https://leetcode.com/problems/tuple-with-same-product\r\n\r\n```python\r\nclass Solution:\r\n    def tupleSameProduct(self, a) -\u003e int:\r\n        return sum(8*comb(n,2)for n in Counter(starmap(mul,combinations(a,2))).values())\r\n\r\nclass Solution:\r\n    def tupleSameProduct(self, a) -\u003e int:\r\n        return sum(4*n*(n-1)for n in Counter(starmap(mul,combinations(a,2))).values())\r\n\r\nclass Solution:\r\n    def tupleSameProduct(self, a) -\u003e int:\r\n        return sum(~-n*n*4for n in Counter(starmap(mul,combinations(a,2))).values())\r\n```\r\n\r\n### Numpy\r\n\r\nYou can use `numpy.convolve` for sliding windows, it's usually shorter than reduce or list comprehension:\r\n\r\n* https://leetcode.com/problems/grumpy-bookstore-owner\r\n\r\n```python\r\nclass Solution:\r\n    def maxSatisfied(self, c: List[int], g: List[int], m: int) -\u003e int:\r\n        t,a=0,[*map(mul,c,g)];[t:=(t,w:=sum(a[i:i+m]))[w\u003et]for i in range(len(c)-m+1)]\r\n        return t+sum(c)-sum(a)\r\n\r\nclass Solution:\r\n    def maxSatisfied(self, c: List[int], g: List[int], m: int) -\u003e int:\r\n        return max(__import__('numpy').convolve(a:=[*map(mul,c,g)],[1]*m))+sum(c)-sum(a)\r\n```\r\n\r\n### Ceil\r\n\r\nYou can replace `ceil(x/k)` with `-(-x//k)` (1 character shorter):\r\n\r\n* https://leetcode.com/problems/maximal-score-after-applying-k-operations\r\n\r\n```python\r\nclass Solution:\r\n    def maxKelements(self, a: List[int], k: int) -\u003e int:\r\n        a.sort();return sum((x:=a.pop(),insort(a,ceil(x/3)))[0]for _ in range(k))\r\n\r\nclass Solution:\r\n    def maxKelements(self, a: List[int], k: int) -\u003e int:\r\n        a.sort();return sum((x:=a.pop(),insort(a,-(-x//3)))[0]for _ in range(k))\r\n```\r\n\r\n## Tables\r\n\r\n### Operators\r\n\r\nThese operators are available in a global namespace (Leetcode includes \"operator\" module by default).\r\n\r\nOperation                   |Syntax             |Function                           \r\n----------------------------|-------------------|-----------------------------------\r\n**Unary**                   |                   |\r\nNegation (Arithmetic)       |`- a`              |`neg(a)`                           \r\nNegation (Logical)          |`not a`            |`not_(a)`                          \r\nPositive                    |`+ a`              |`pos(a)`                           \r\nTruth Test                  |`obj`              |`truth(obj)`                       \r\nBitwise Inversion           |`~ a`              |`invert(a)`                        \r\n**Binary**                  |                   |\r\nAddition                    |`a + b`            |`add(a, b)`                        \r\nConcatenation               |`seq1 + seq2`      |`concat(seq1, seq2)`               \r\nContainment Test            |`obj in seq`       |`contains(seq, obj)`               \r\nDivision                    |`a / b`            |`truediv(a, b)`                    \r\nDivision                    |`a // b`           |`floordiv(a, b)`                   \r\nBitwise And                 |`a \u0026 b`            |`and_(a, b)`                       \r\nBitwise Exclusive Or        |`a ^ b`            |`xor(a, b)`                        \r\nBitwise Or                  |`a \\| b`           |`or_(a, b)`                        \r\nExponentiation              |`a ** b`           |`pow(a, b)`                        \r\nIdentity                    |`a is b`           |`is_(a, b)`                        \r\nIdentity                    |`a is not b`       |`is_not(a, b)`                     \r\nIndexed Deletion            |`del obj[k]`       |`delitem(obj, k)`                  \r\nIndexing                    |`obj[k]`           |`getitem(obj, k)`                  \r\nLeft Shift                  |`a \u003c\u003c b`           |`lshift(a, b)`                     \r\nModulo                      |`a % b`            |`mod(a, b)`                        \r\nMultiplication              |`a * b`            |`mul(a, b)`                        \r\nMatrix Multiplication       |`a @ b`            |`matmul(a, b)`                     \r\nRight Shift                 |`a \u003e\u003e b`           |`rshift(a, b)`                     \r\nString Formatting           |`s % obj`          |`mod(s, obj)`                      \r\nSubtraction                 |`a - b`            |`sub(a, b)`                        \r\nOrdering (Less Than)        |`a \u003c b`            |`lt(a, b)`                         \r\nOrdering (Less or Equal)    |`a \u003c= b`           |`le(a, b)`                         \r\nEquality                    |`a == b`           |`eq(a, b)`                         \r\nDifference (Not Equal)      |`a != b`           |`ne(a, b)`                         \r\nOrdering (Greater or Equal) |`a \u003e= b`           |`ge(a, b)`                         \r\nOrdering (Greater Than)     |`a \u003e b`            |`gt(a, b)`                         \r\n**Ternary**                 |                   |\r\nIndexed Assignment          |`obj[k] = v`       |`setitem(obj, k, v)`               \r\nSlice Assignment            |`seq[i:j] = values`|`setitem(seq, slice(i, j), values)`\r\nSlice Deletion              |`del seq[i:j]`     |`delitem(seq, slice(i, j))`        \r\nSlicing                     |`seq[i:j]`         |`getitem(seq, slice(i, j))`        \r\n\r\nThe same naming goes for the member functions, but with underscores, e.g. `(1).__lt__`.\r\n\r\n### Precedence\r\n\r\nKnowing precedence helps to cut parens. For example, you can replace `(n-1)` with `~-n` (binary negation).\r\n\r\nPrecedence|Operators                                     |Description                                                |Associativity\r\n----------|----------------------------------------------|-----------------------------------------------------------|-------------\r\n1         |`()`                                          |Parentheses                                                |Left to right\r\n2         |`x[i], x[i:j]`                                |Subscription, slicing                                      |Left to right\r\n3         |`await x`                                     |Await expression                                           |N/A          \r\n4         |`**`                                          |Exponentiation                                             |Right to left\r\n5         |`+x, -x, ~x`                                  |Positive, negative, bitwise NOT                            |Right to left\r\n6         |`*, @, /, //, %`                              |Multiply (matrix), division, remainder                     |Left to right\r\n7         |`+, –`                                        |Addition and subtraction                                   |Left to right\r\n8         |`\u003c\u003c, \u003e\u003e`                                      |Shifts                                                     |Left to right\r\n9         |`\u0026`                                           |Bitwise AND                                                |Left to right\r\n10        |`^`                                           |Bitwise XOR                                                |Left to right\r\n11        |`\\|`                                          |Bitwise OR                                                 |Left to right\r\n12        |`in, not in, is, is not, \u003c, \u003c=, \u003e, \u003e=, !=, ==`|Comparisons, membership tests, identity tests              |Left to Right\r\n13        |`not x`                                       |Boolean NOT                                                |Right to left\r\n14        |`and`                                         |Boolean AND                                                |Left to right\r\n15        |`or`                                          |Boolean OR                                                 |Left to right\r\n16        |`if-else`                                     |Conditional expression                                     |Right to left\r\n17        |`lambda`                                      |Lambda expression                                          |N/A          \r\n18        |`:=`                                          |Assignment expression (walrus)                             |Right to left\r\n\r\n### Itertools\r\n\r\nSee https://docs.python.org/3/library/itertools.html\r\n\r\n#### Infinite operators\r\n\r\nIterator   | Arguments       | Results                                          | Example                              \r\n-----------| --------------- | ------------------------------------------------ | -------------------------------------\r\n`count()`  | [start[,step]]  | start, start+step, start+2\\*step, ...            | `count(10)` → 10 11 12 13 14 ...\r\n`cycle()`  | p               | p0, p1, … plast, p0, p1, ...                     | `cycle('ABCD')` → A B C D A B C D ...\r\n`repeat()` | elem [,n]       | elem, elem, elem, ... endlessly or up to n times | `repeat(10, 3)` → 10 10 10\r\n\r\n#### Iterators terminating on the shortest input sequence\r\n\r\nIterator                | Arguments                   | Results                                         | Example                                                   \r\n----------------------- | --------------------------- | ----------------------------------------------- | ----------------------------------------------------------\r\n`accumulate()`          | p [,func]                   | p0, p0+p1, p0+p1+p2, ...                        | `accumulate([1,2,3,4,5])` → 1 3 6 10 15                 \r\n`batched()`             | p, n                        | (p0, p1, ..., p_n-1), ...                       | `batched('ABCDEFG', n=3)` → ABC DEF G                   \r\n`chain()`               | p, q, ...                   | p0, p1, ... plast, q0, q1, ...                  | `chain('ABC', 'DEF')` → A B C D E F                     \r\n`chain.from_iterable()` | iterable                    | p0, p1, ... plast, q0, q1, ...                  | `chain.from_iterable(['ABC', 'DEF'])` → A B C D E F     \r\n`compress()`            | data, selectors             | (d[0] if s[0]), (d[1] if s[1]), ...             | `compress('ABCDEF', [1,0,1,0,1,1])` → A C E F           \r\n`dropwhile()`           | predicate, seq              | seq[n], seq[n+1], starting when predicate fails | `dropwhile(lambda x: x\u003c5, [1,4,6,3,8])` → 6 3 8         \r\n`filterfalse()`         | predicate, seq              | elements of seq where predicate(elem) fails     | `filterfalse(lambda x: x\u003c5, [1,4,6,3,8])` → 6 8         \r\n`groupby()`             | iterable[, key]             | sub-iterators grouped by value of key(v)        | `groupby(['A','B','DEF'], len)` → (1, A B) (3, DEF)     \r\n`islice()`              | seq, [start,] stop [, step] | elements from seq[start:stop:step]              | `islice('ABCDEFG', 2, None)` → C D E F G                \r\n`pairwise()`            | iterable                    | (p[0], p[1]), (p[1], p[2])                      | `pairwise('ABCDEFG')` → AB BC CD DE EF FG               \r\n`starmap()`             | func, seq                   | func(\\*seq[0]), func(\\*seq[1]), ...             | `starmap(pow, [(2,5), (3,2), (10,3)])` → 32 9 1000      \r\n`takewhile()`           | predicate, seq              | seq[0], seq[1], until predicate fails           | `takewhile(lambda x: x\u003c5, [1,4,6,3,8])` → 1 4           \r\n`tee()`                 | it, n                       | it1, it2, ... itn splits one iterator into n    |                                                       \r\n`zip_longest()`         | p, q, ...                   | (p[0], q[0]), (p[1], q[1]), ...                 | `zip_longest('ABCD', 'xy', fillvalue='-')` → Ax By C- D-\r\n\r\n#### Combinatoric iterators\r\n\r\nFunction | Arguments | Results\r\n---------|-----------|---------\r\n`product()` | p, q, ... [repeat=1] | cartesian product, equivalent to a nested for-loop\r\n`permutations()` | p[, r] | r-length tuples, all possible orderings, no repeated elements\r\n`combinations()` | p, r | r-length tuples, in sorted order, no repeated elements\r\n`combinations_with_replacement()` | p, r | r-length tuples, in sorted order, with repeated elements\r\n\r\nExamples                                   | Results\r\n-------------------------------------------|---------------------------------------------------\r\n`product('ABCD', repeat=2)`                | AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD\r\n`permutations('ABCD', 2)`                  | AB AC AD BA BC BD CA CB CD DA DB DC\r\n`combinations('ABCD', 2)`                  | AB AC AD BC BD CD\r\n`combinations_with_replacement('ABCD', 2)` | AA AB AC AD BB BC BD CC CD DD\r\n\r\n## Notes\r\n\r\n* An expression like `x\u0026(x-1)==0` is useful to check if unsigned `x` is power of 2 or 0 (Kernighan, rightmost bit).\r\n* Unless the following token starts with e or E, you can remove the space following a number. E.g. `i==4 and j==4` becomes `i==4and j==4`.\r\n* Instead of range(x), you can use the * operator on a list of anything, e.g. `[1]*8` can replace `range(8)` (unless you really need the counter value).\r\n* Conditions like `if i\u003clen(r)` may be replaced with `if r[i:]`, it's 3 characters shorter.\r\n* You can replace `set(n)` with `{*n}` (2 characters shorter).\r\n* You can convert bool with `~~()` instead of `int()` (as in js) or prepend with a single `+` (5 characters shorter).\r\n* You can subtract 1 or replace `not` operator with bitwise negation `~-` to save on space (1-5 characters shorter).\r\n* You can check for set membership with `{x}\u0026s` instead of `x in s` (1 character shorter).\r\n* Very often `x==0` can be replaced with `x\u003c1` (1 character shorter).\r\n* A condition like `h\u003ei\u003e=0\u003c=j\u003cw` can be written as `h\u003ei\u003e-1\u003cj\u003cw` (1 character shorter).\r\n* You can replace `q and q[-1]==c` with `q[-1:]==[c]` (3 characters shorter).\r\n\r\n## References\r\n\r\n* [Don't Piss down my back and tell me it's raining: Notebook for Sarcastic, Witty, and Sharp Tongued One Liners](https://www.amazon.com/Dont-Piss-down-back-raining/dp/B08ZQGV1XH)\r\n* [They're not characters at all, they're just brilliant repositories of fantastic, killer one-liners](https://youtu.be/8k2AbqTBxao?t=251)\r\n* [Python One-Liners: Write Concise, Eloquent Python Like a Professional](https://www.amazon.com/Python-One-Liners-Concise-Eloquent-Professional/dp/1718500505)\r\n* [Python One-Liners - Concise Python Code](https://www.amazon.com/gp/product/1718500505)\r\n* [One-line coder makes me depressed](https://redd.it/15wz7n7)\r\n* [Tips for Golfing in Python](https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python)\r\n* [King of One-Liners](https://youtu.be/DbbKaM8_LUc)\r\n\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoric%2Foneliners","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjoric%2Foneliners","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoric%2Foneliners/lists"}