Wednesday, December 25, 2024
Google search engine
HomeLanguagesCode Golfing in Python

Code Golfing in Python

Code Golf in Python refers to attempting to solve a problem using the least amount of characters possible. Like in Golf, the low score wins, the fewest amount of characters “wins”. 

Python is a fantastic language for code golfing due to backward compatibility, quirks, it being a high-level language, and all the coercion. So, here we will look at some Code golfing techniques in Python language. 

Using loops

Collapse two numerical loops: Suppose you are iterating over a matrix of m rows and n columns. Instead of two nested for loops, one for the row and one of the columns, it’s usually shorter to use a single loop to iterate over the m*n matrix. 

Original Code : 

m = n = 3
for i in range(m):
    for j in range(n):
        print(i, j)

Golfed Code :  

m = n = 3
for i in range(m*n):
    print(i//n, i%n)

This technique is not limited to only two nested loops, we can even write the same loop for 3 or more nested loops  

m, n, o = 2, 3, 4
for k in range(m*n*o):
    print(k//n//o, k%(n*o), k%o)

Using operators

  • Addition or Subtraction by 1: For integer n you can write 
    • -~n is equivalent to n+1
    • ~-n is equivalent to n-1

This works because the bit flip ~x equals -x-1. This uses the same number of characters, but can indirectly cut spaces or parents for operator precedence.

  • Membership in Set: We write set in Python as S = {1, 2, 3, 4, 5}. To check whether an element e exists in Set S or not we can check the condition as {e}&S 

    Original Code: 

S = {1, 2, 3, 4, 5, 6, 7}
if 5 in S:
    print("Present")
else:
    print("Absent")

Golfed Code: 

S = {1, 2, 3, 4, 5, 6, 7}
if {5}&S:
    print("Present")
else:
    print("Absent")
  • Sibling of AND operator: When we have two boolean or integer values, a and b, if we want to find out if both a and b are true, use * instead of and

    Original Code: 

if a and b:
    print("Lazyroar")
else:
    print("neveropen")

Golfed Code: 

if a*b:
    print("Lazyroar")
else:
    print("neveropen")
  • Sibling of OR operator: When we have two boolean or integer values, a and b, if we want to find out if any one from a and b is true or both, use | instead of or

    Original Code: 

if a or b:
    print("Lazyroar")
else:
    print("neveropen")

Golfed Code: 

if a|b:
    print("Lazyroar")
else:
    print("neveropen")
  • Use += instead of append: Instead of using append for adding one item to an existing list, we can use += operator. 

    Original Code: 

A.append(B)

Golfed Code: 

A+=B,

Note: B, here creates a one-element tuple which can be used to extend A just like [B] in A+=[B]. 

  • Use += instead of extend: Instead of using extend for merging one list into another at the end, we can use += operator. 

    Original Code: 

A.extend(B)

Golfed Code: 

A+=B
  • Magical Comparison Operators: We face many situations in which we have to compare a single variable with different values, and generally we defend them by different comparisons and combining them with AND operator. But Python allows us to put all comparison operators in a single line without using the AND operator. 
    Original Code: 
if a>1 and a<10:
    print(a)

Golfed Code: 

if 1<a<10:
    print(a)

Note: We can use this technique for multiple variables also at the same time. 

Original Code: 

if a > 10 and b > 10 and 30 > a and 50 > b:
    print(a)

Golfed Code: 

if 30 > a > 10 < b < 50:
    print(a)

Using Functions

  • Sibling of Floor function: Suppose we want to find the floor value of a real number, we generally import floor function from math and then apply on the number. But we can simply apply the floor division with 1, which will give us a fruitful result. 

    Original Code: 

from math import floor
n = 3/2
print(floor(n))

Golfed Code: 

n = 3/2
print(n//1)
  • Sibling of Ceil function: Suppose we want to find the ceil value of a real number, we generally import ceil function from math and then apply on the number. But we can do this operation in a more beautiful manner by first multiplying with -1 and then apply floor division with 1 and again multiply with -1. 

    Original Code: 

from math import ceil
n = 3/2
print(ceil(n))

Golfed Code: 

n = 3/2
print(-(-n//1))
  • Lambda functions: Lambda definition does not include a “return” statement, it always contains an expression which is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions. 

    Original Code: 

def c(a):
  if a < 3: return a-5
  else: return a+5

Golfed Code: 

c=lambda a:a<3and a-5or a+5
  • To get the entire alphabet string: We can use the map function of python to get the string of whole alphabet set. 

    Original code: 

string = 'abcdefghijklmnopqrstuvwxyz'
or 
string = [chr(i+97)for i in range(26)]

Golfed Code: 

string = map(chr,range(97,123))

Using indexing

  • Indexing Technique for conditions: When we have a certain condition which will give the answer in the form of small integers then we can use that in integer index in list or tuple to get our final answer. 

    Original Code: 

if a<b:return a
else:return b

Golfed Code: 

return (b, a)[a<b]
  • Reverse the Sequence: We can reverse any list sequence using the good alien smiley face. 

    Original Code: 

string = 'neveropen'
for i in range(len(string)-1,-1,-1):
    print(string[i])

Golfed Code: 

string = 'neveropen'
for i in string[::-1]:
    print(i)
  • Use ~ to index from the back of a list: If L is a list, use L[~i] to get the i’th element from the back. This is the i’th element of the reverse of L. The bit complement ~i equals -i-1, and so fixes the off-by-one error from L[-i]. 

    Original Code: 

string = 'neveropen'
for i in range(len(string)-1,-1,-1):
    print(string[i])

Golfed Code: 

for i in range(len(string)):
    print(string[~i])
  • Print the items of the list: We can print the items of a list by using the * operator with the name of the list instead of looping through the list. 

    Original Code: 

A = [1,2,3,4,5,6,7]
for i in A:
    print(i,end = ' ')

Golfed Code: 

A = [1,2,3,4,5,6,7]
print(*A) 

Using assignment

  • Assigning the same values to multiple variables: We can assign the same value to multiple variables either in a single line or multiple lines. 
    Original Code: 
# multiple lines
a = 0
b = 0
c = 0

# single line
a,b,c = 0,0,0

Golfed Code: 

a = b = c = 0
  • Assigning same or different characters to variable: We can assign the same of different characters to multiple variables either in a single line or multiple lines. 
    Original Code: 
# multiple lines
a = 'p'
b = 'q'
c = 'r'

# single line
a,b,c = 'p','q','r'

Golfed Code: 

a,b,c = 'pqr'

Using conversion

  • Converting iterables into the list: Imagine you have any ordered iterable like a tuple or string but you want to convert it into a list, so you can do this with * operator. 

    Original Code: 

a = (2,3,5,7,11)
x = list(a)

a = 'Lazyroarforgeek'
x = list(a)

Golfed Code: 

a = (2,3,5,7,11)
*x, = a

a = 'neveropen'
*x, = a
  • Converting iterables into the Set: Imagine you have any iterable like a list, tuple or string but you want to convert it into a Set, so you can do this with * operator. 

    Original Code: 

a = (2,3,5,7,11)
x = set(a)

a = [2,3,5,7,11]
x = set(a)

a = 'neveropen'
x = set(a)

Golfed Code: 

a = (2,3,5,7,11)
x = {*a}

a = [2,3,5,7,11]
x = {*a}

a = 'neveropen'
x = {*a}
  • Converting iterables into the Tuple: Imagine you have any iterable like a list, set, or string but you want to convert it into a Tuple, so you can do this with * operator. 

    Original Code: 

a = (2,3,5,7,11)
x = tuple(a)

a = [2,3,5,7,11]
x = tuple(a)

a = 'neveropen'
x = tuple(a)

Golfed Code: 

a = (2,3,5,7,11)
x = (*a,)

a = [2,3,5,7,11]
x = (*a,)

a = 'neveropen'
x = (*a,)

During joining of different iterables 

  • Joining multiple Lists: We can join the multiple lists using + operator, but for code golfing we can do the same using * operator. 

    Original Code: 

T = [2,3,4,5,6,7,8,9]
new_T = [1]+T+[10]

Golfed Code: 

T = [2,3,4,5,6,7,8,9]
new_T = [1,*T,10]
  • Joining multiple Lists: We can join the multiple lists using + operator, but for code golfing we can do the same using * operator. 

    Original Code: 

T = (2,3,4,5,6,7,8,9)
new_T = (1,)+T+(10,)

Golfed Code: 

T = (2,3,4,5,6,7,8,9)
new_T = (1,*T,10)

RELATED ARTICLES

Most Popular

Recent Comments