In code golfing you have to complete a given task using as few characters as possible.
The c̵o̵d̵e̵f̵i̵g̵h̵t̵s̵ codesignal.com site runs code golfing competitions daily. Through the leaderboard you can learn techniques in minimizing code.
x + 1 == ~-x
At a glance both sides of that equality have the same amount of characters. But
~-x is useful in calculations where you’d like to avoid parenthesis. E.g. compare
Which takes 7 characters down to 5.
x *= x
Probably the shortest way to square a variable which is 4 characters instead of the 5:
You can use booleans in multiplication, and addition (e.g. to increment a counter). Check out this golf by miguel_r35 on codesignal. Two
if statements were removed thanks to the predictable numerical boolean value.
# Discover the length of the longest index range that sums
# to less than or equal to `e` (energy)
def roverTour (t, e):
i = len(t) # start off with the maximum possible value
for x in t:
f = x > e # did we run out of energy
e += f*t[-i] - x # using multiply, add when `x > e`
i -= f # decrement using a boolean when `x > e`
Transpose a matrix with zip(*seq)
This can be useful when you need to operate on the columns of a 2D array. Note that in Python 3
zip returns an iterator.
>>> list(zip(*[[1, 2, 3], [4, 5, 6]]))
[(1, 4), (2, 5), (3, 6)]
This solution by dav23r verifies the sum of the columns equals the sum of the rows:
for x, y in zip(map(sum, arr), map(sum, zip(*arr))):
if x != y: