# Python basic grammar / algorithm

Make a note because I forget it every time. Updated from time to time.

# Basic grammar

## Tuple

(1, 2, 3) etc. Cannot be changed. The list can be changed.

## How to receive the list

``````L = [[1, 2], [3, 4]]
for x, y in L:
print(x, y)

# 1, 2
# 3, 4
``````

## List slice

``````[start:end:step]

#Reverse order
[::-1]
``````

## sort

``````L.sort()
L = sorted(L)
``````

## Get the quotient and remainder of the division at the same time

``````a, b = divmod(10, 3)
print(a, b)
# 3 1
``````

## Returns the remainder of x ** y divided by z

``````pow(x, y, z)
``````

## n is at most 10

``````min(10, n)
``````

## Factorial

``````math.factorial(5)
``````

## permutation

``````# p = n! / (n-r)!Than
def permutations_count(n, r):
return math.factorial(n) // math.factorial(n - r)
``````

## combination

``````# c = n! / (r! * (n - r)!)Than
def combinations_count(n, r):
return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
``````

## Greatest common divisor

``````# a>b
def gcd(a, b)
while b:
a, b = b, a % b

#Or
import math
print(math.gcd(6, 4))
``````

## Least common multiple

``````def lcm(a, b):
return a * b // gcd(a, b)

#Or
import math
print(math.lcm(6, 4))
``````

## divisor

``````def divisor(n):
lower_divisors, upper_divisors = [], []
i = 1
while i * i <= n:
if n % i == 0:
lower_divisors.append(i)
if i != n // i:
upper_divisors.append(n // i)
i += 1
return lower_divisors + upper_divisors[::-1]
``````

## Prime factorization

``````def prime_decomposition(n):
i = 2
table = []
while i * i <= n:
while n % i == 0:
n /= i
table.append(i)
i += 1
if n > 1:
table.append(n)
return table
``````

## Primality test

``````def is_prime(n):
for i in range(2, n+1):
if i * i > n:
break
if n % i == 0:
return False
return n != 1
``````

## Convert to an octal string

``````str.format(i, 'o')
``````