Golfing is the art of use as few characters as possible to implement an algorithm.
If you want some inspirations about rules or if you just want to shorten your code, here are some tips.
Instead of writing
if condition:
print(a)
else:
print(b)
you can write
print([b,a][condition])
However, Python will eagerly evaluate every variable, if you need to lazily evaluate, you can alternatively write:
print(a if condition else b)
This also works for reasignement
For example
if condition:
v += 5
else:
v += 2
becomes
v+=2+3*condition
for i in range(n):
for j in range(m):
do_something(i, j)
can become
for i in range(n*m):
do_something(i//n,j%m)
for i in range(n):
do_something_without_i()
can become
for i in'|'*n:
do_something_without_i()
l=list(map(int, input().split()))
can become
*l,=map(int,input().split())
l.append(a)
=> l+=[a]
a=l[0]
=> a,_*=l
a=l[-1]
=> _*,a=l
math.floor(n)
=> n//1
math.ceil(n)
=> -(-n//1)
In most exercises, you can terminate your program by raising an exception.
n=int(input())
for i in range(n):
do_stuff(input())
can become
input()
while 1:
do_stuff(input())
If you have multiple statement in a row, you can separate them by ;
for i in range(n):print(i);print(i+1)
Python accepts any kind of tabulations. Therefore, you can use a single space:
while True:
pass