How to use Functions In Python
- 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))
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.