Nested Lists
Published
Nested Lists
Here are some examples of nested lists I found interesting while practicing in Leetcode. Sometimes you need an example to create you own.
Richest Customer Wealth
1return reduce(lambda a, b: a if a > (s:=sum(b)) else s, accounts, 0)XOR Operation in an Array
1return functools.reduce(lambda a, b: a ^ b, [start + 2 * i for i in range(n)])Decode XORed Array
1return list(accumulate([first] + A, lambda x, y: x ^ y))2
3return [first] + [first:=first^e for e in encoded]Merge Strings Alternately
1return ''.join(a + b for a, b in zip_longest(w1, w2, fillvalue=''))2
3return ''.join(chain.from_iterable(zip_longest(w1, w2, fillvalue='')))To Lower Case
1return "".join(chr(ord(c) + 32) if "A" <= c <= "Z" else c for c in str)Minimum Time Visiting All Points
1return sum(max(abs(cur[0] - prev[0]), abs(cur[1] - prev[1])) for cur, prev in zip(points, points[1 :]))2
3return sum(max(abs(c - p) for c, p in zip(cur, prev)) for cur, prev in zip(points, points[1 :]))Remove Outermost Parentheses
1opened += 1 if c == '(' else -12
3opened += c == '(' ? 1 : -1Split a String in Balanced Strings
1res += r == 0Unique Morse Code Words
1return len(set([''.join([abc[ord(j) - 97] for j in i]) for i in words]))1return len({''.join(d[ord(i) - ord('a')] for i in w) for w in words})Flipping an Image
1return [[1 ^ i for i in reversed(row)] for row in A]Matrix Diagonal Sum
1return sum(sum(r[j] for j in {i, len(r) - i - 1}) for i, r in enumerate(m))Decrypt String from Alphabet to Integer Mapping
1return ''.join(chr(int(i[:2]) + 96) for i in re.findall(r'\d\d#|\d', s))2
3return "".join([chr(int(n)+96) for n in findall(r'..(?=#)|\d', s)]) -> drop "#" right in regular expression:4
5return re.sub[r'\d{2}#|\d', lambda x: chr(int(x.group(](:2))+96), s)Split a String in Balanced String
1for s in S: c, m = c + D[s], m + (c == 0)Execute dict.get on every char in s, e.g. {'L': 1, 'R': -1}[s[0]] , if s[0] is 'L' then result is 1, and -1 when 'R', etc
1return list(acc(1 if c == 'L' else -1 for c in s)).count(0)2
3return list(acc(map(' L'.find, s))).count(0)4
5return list(acc(map({'L': 1, 'R': -1}.get, s))).count(0)Number of Students Doing Homework at a Given Time
1class Solution:busyStudent=lambda s,a,e,q:sum(q in range(a[i],e[i]+1)for i in range(len(a)))Increasing Decreasing String
1for i in range(10): print(i, ~i)1for c in sorted(cnt.keys()) if asc else reversed(sorted(cnt.keys())):Generate a String with Characters That Have Odd Counts
1return ("a" *(n-1) + "b" if n%2 == 0 else "b"* n)Merge Two Binary Trees
Using t1 and t1.left as a shortcut for t1.left if t1 is not None else None
1ans.left = self.mergeTrees(t1 and t1.left, t2 and t2.left)Reverse Words in a String III
1return " ".join(map(lambda x: x[::-1], s.split()))