Finally solved 100 LC problems(easy ones mostly). Some most frequently used notes:
Operators
//: floor division, it dumps the digits after the decimal
/: devision (version diff)
%: modulus, returns the value of the remainder
^: XOR, XOR gate (sometimes EOR, or EXOR and pronounced as Exclusive OR) is a digital logic gate that gives a true (1 or HIGH) output when the number of true inputs is odd. An XOR gate implements an exclusive or; that is, a true output results if one, and only one, of the inputs to the gate is true.
e.g. a^b^b = a
Functions
set()
Used to convert any of the iterable to the distinct element and sorted sequence of iterable elements, commonly called Set.
sort()
Some examples related with sort:
1
2
3
sorted(range(len(a)), key=lambda i: a[i])[-2:]
sorted(range(len(a)), key=lambda i: a[i], reverse=True)[:2]
A.sort(reverse = True)
lamda
A small anonymous function.
collections.Counter
A counter is a dict subclass for counting hashable objects.
Example: 1213 Intersection of Three Sorted Arrays
1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def arraysIntersection(self, arr1, arr2, arr3):
"""
:type arr1: List[int]
:type arr2: List[int]
:type arr3: List[int]
:rtype: List[int]
"""
import collections
counter = collections.Counter(arr1 + arr2 + arr3).items()
return [k for k, v in counter if v == 3]
reduce(fun, seq)
It applies a rolling computation to sequential pairs of values in a list.
1
2
3
4
5
from functools import reduce
for num in list:
product = product * num
""" equals to """
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])