Python Templates

Python Templates

Use these templates if Python is allowed.

Basic input

n = int(input())
print(n)

Array input

n = int(input())
a = list(map(int, input().split()))

Multiple test cases

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))

String input

Single word:

s = input().strip()

Full line:

s = input()

Prime check

def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    i = 3
    while i * i <= n:
        if n % i == 0:
            return False
        i += 2
    return True

GCD and LCM

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

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

Frequency

freq = {}
for x in a:
    freq[x] = freq.get(x, 0) + 1

Or:

from collections import Counter
freq = Counter(a)

Reverse string

rev = s[::-1]

Sort

a.sort()

Two pointers

a.sort()
l, r = 0, len(a) - 1
while l < r:
    total = a[l] + a[r]
    if total == target:
        print("YES")
        break
    elif total < target:
        l += 1
    else:
        r -= 1
else:
    print("NO")