Dev & Scripting » Coding Challenges » Code Golf Cheatsheet
Code golf = make the shortest code to solve a problem.
This is not only a code golf cheatsheet, it shows a lot of tricks that we can do with different programming languages.
Table of contents
Python Code Golf Cheatsheet
# STRINGS
s[::-1] # reverse string
s*3 # repeat string
s.count("a") # count substring
"a"in s # membership test
min(s),max(s) # lexicographic min/max char
s.split() # split on whitespace
",".join(a) # join iterable into string
"".join(map(str,a)) # join numbers
s.lower(),s.upper() # case transform
s.swapcase() # swap lower/upper
s.isalpha() # letters only
s.isalnum() # letters + digits
s.isdigit() # digits only
# CONVERSIONS
int(s) # string → int
int(s,b) # base-b → int
bin(n)[2:] # int → binary
hex(n)[2:] # int → hex
oct(n)[2:] # int → octal
chr(n) # int → char
ord(c) # char → int
str(n) # anything → string
# FORMAT STRINGS
f"{x:.2f}" # float with 2 decimals
f"{x:.0f}" # rounded float
f"{n:03}" # zero-pad integer
f"{n:b}" # binary format
f"{n:x}" # hex format
"%.2f"%x # short float formatting
"%d"%x # integer formatting
# ITERABLES
[*map(f,a)] # map without list()
[*filter(f,a)] # filter without list()
[x for x in a] # comprehension
[x for x in a if c] # filtered comprehension
sum(a) # sum elements
len(a) # length
sorted(a) # sort iterable
sorted(numbers, key=lambda n: sum(map(int, str(n)))) # example of key parameter: sort numbers by the sum of their digits
a[::-1] # reverse list
max(a),min(a) # extrema
list(set(a)) # remove duplicates
"".join(a) # join chars
# MATH/LOGIC/BITS
x>>1 # divide by 2 (positive ints)
x<<1 # multiply by 2
x&1 # parity (odd/even)
x^y # xor
x**.5 # square root
round(x,1) # round to 1 decimal
abs(x) # absolute value
divmod(a,b) # quotient and remainder
x<y<z # chained comparison
a and b # logical AND
a or b # logical OR
# LAMBDAS/EXPRESSIONS
lambda x:x*x # anonymous function
(lambda x:x*x)(n) # inline lambda call
a if c else b # ternary expression
# DICTS/SETS
d.get(k,0) # safe dict access
{k:v for k,v in a} # dict comprehension
set(a) # unique elements
len(set(a)) # count uniques
# INPUT/OUTPUT
I=input # when more than one input(), use I() for shorter code
int(input()) # read int
map(int,input().split())# read ints
print(*a) # space-separated output
# USEFUL ONE LINERS
sum(map(int,input().split())) # sum input numbers
print(*sorted(map(int,input().split()))) # sort input
print("YES"if c else"NO") # conditional output
all(a) # all True
any(a) # any True
["even","odd"][d%2] # will return "even" if d%2 equals 0 or "odd" if it equals 1