Code snippets (CPP version)
CPP means competitive programming in Python :D
Some code snippets in Python that I concluded so that I can do LeetCode faster.
Input & output
In some platforms like Codeforces or UVA, sometimes reading input is complicated if you're not familiar with it.
Read integer input
Read an integer in a line:
n = int(input())
Read many integers in a line:
9, 10
na,nb = map(int, input().split())
> na: 9, nb: 10
Read many lines into an array, use list(map(int, input().split())):
2 4
5 6
a = []
for i in range(2):
  a.extend(list(map(int,input().split())))
> a: [2, 4, 5, 6]
Built-in functions
Python has many things that has built up for us. Why not using them?
Max, min
Use max, min for faster finding:
current_max = max(current_max, array[i])
current_min = min(current_min, array[i])
Sorting
Use sort to sort array (mutable). The complexity is usually .
arr.sort()
Use sorted for immutable:
sorted_arr = sorted(arr)
Using lambda
Lambda function is an anonymous function with 1 expression. You can prefer something like (x) => x + 1 in JavaScript for example.
x = lambda a : a + 10
print(x(5)) # 15
You can use lambda function with map, filter, etc.
Note that map returns map object so we have to convert it to array using list()
arr = [1, 2, 3, 4, 5]
list(map(lambda n: n * 2, arr))
> [2, 4, 6, 8, 10]
One example that we want addition of arrays. For example, [1, 2, 1, 0] plus [0, 1, 2, 1] like this:
 1 2 1 0
 0 1 2 1
 1 3 3 1 <-
Simply add is not going to work:
sum = [1, 2, 1, 0] + [0, 1, 2, 1]
> sum: [1, 2, 1, 0, 0, 1, 2, 1]
So we use lambda function with map() and convert it using list():
arr1 = [1, 2, 1, 0]
arr2 = [0, 1, 2, 1]
sum = list(map(lambda x, y: x + y, arr1, arr2))
> sum: [1, 3, 3, 1]
Example:
Array tips
Declare 2-dimension array
Instead of:
2d_arr = [0] * rows
for i in range(rows):
  res[i] = [0] * cols
# for example with rows = 3, cols = 4:
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
0 0 0 0
0 0 0 0
0 0 0 0
Do these:
2d_arr = [[0 for _ in range(cols)] for _ in range(rows)]
Note that we don't use arr = [] * n, cause this is not create anything. So we had to have initial value for array.
Declare
When we do things related to 2-D array, remember divide (//) and module (%).
Examples
Data structures
Set
Counter
When counter problems that requires counting elements repeat, etc. Example is the problem that ask for repeat of each character in a string.
We can use Counter from collections library, this data structure creates a dictionary that has element is key, value is count variable.
from collections import Counter
# create dictionary stores <objects,counts> as <key,value>
cnt = Counter('hello world')
cnt['o']  # 2, count of character 'c'
cnt['o'] += 1