Nested Lists
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.
return reduce(lambda a, b: a if a > (s:=sum(b)) else s, accounts, 0)
Source: richest-customer-wealth
return functools.reduce(lambda a, b: a ^ b, [start + 2 * i for i in range(n)])
Source: xor-operation-in-an-arra
return list(accumulate([first] + A, lambda x, y: x ^ y))
return [first] + [first:=first^e for e in encoded]
Source: decode-xored-array
return ''.join(a + b for a, b in zip_longest(w1, w2, fillvalue=''))
return ''.join(chain.from_iterable(zip_longest(w1, w2, fillvalue='')))
Source: merge-strings-alternately
return "".join(chr(ord(c) + 32) if "A" <= c <= "Z" else c for c in str)
Source: to-lower-case
return sum(max(abs(cur[0] - prev[0]), abs(cur[1] - prev[1])) for cur, prev in zip(points, points[1 :]))
return sum(max(abs(c - p) for c, p in zip(cur, prev)) for cur, prev in zip(points, points[1 :]))
Source: minimum-time-visiting-all-points
opened += 1 if c == '(' else -1
opened += c == '(' ? 1 : -1
Source: remove-outermost-parentheses
res += r == 0
Source: split-a-string-in-balanced-strings
return len(set([''.join([abc[ord(j) - 97] for j in i]) for i in words]))
Source: unique-morse-code-words
return len({''.join(d[ord(i) - ord('a')] for i in w) for w in words})
Source: unique-morse-code-words
return [[1 ^ i for i in reversed(row)] for row in A]
Source: flipping-an-image
return sum(sum(r[j] for j in {i, len(r) - i - 1}) for i, r in enumerate(m))
Source: matrix-diagonal-sum
return ''.join(chr(int(i[:2]) + 96) for i in re.findall(r'\d\d#|\d', s))
return "".join([chr(int(n)+96) for n in findall(r'..(?=#)|\d', s)]) -> drop "#" right in regular expression:
return re.sub[r'\d{2}#|\d', lambda x: chr(int(x.group(](:2))+96), s)
Source: decrypt-string-from-alphabet-to-integer-mapping
for s in S: c, m = c + D[s], m + (c == 0)
Source: split-a-string-in-balanced-string
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
return list(acc(1 if c == 'L' else -1 for c in s)).count(0)
return list(acc(map(' L'.find, s))).count(0)
return list(acc(map({'L': 1, 'R': -1}.get, s))).count(0)
Source: split-a-string-in-balanced-strings
class Solution:busyStudent=lambda s,a,e,q:sum(q in range(a[i],e[i]+1)for i in range(len(a)))
Source: number-of-students-doing-homework-at-a-given-time
for i in range(10): print(i, ~i)
Source: increasing-decreasing-string
for c in sorted(cnt.keys()) if asc else reversed(sorted(cnt.keys())):
Source: increasing-decreasing-string
return ("a" *(n-1) + "b" if n%2 == 0 else "b"* n)
Source: generate-a-string-with-characters-that-have-odd-counts
Using t1
and t1.left
as a shortcut for t1.left
if t1
is not None
else None
ans.left = self.mergeTrees(t1 and t1.left, t2 and t2.left)
Source: merge-two-binary-trees
return " ".join(map(lambda x: x[::-1], s.split()))
Source: reverse-words-in-a-string-iii