r/shittyprogramming • u/GlueDonkey • Apr 19 '21
7 line "is even" function 🤯
I've attempted to solve the infamous "is even" problem, and I've come up with something that is both short (only 7 lines), and extremely fast (I tested with the number 99999999 and it only takes about 3 seconds)
behold:
def is_even(num):
s = "\\"
try:
eval(f"\"{s*num}\"")
return True
except SyntaxError:
return False
how did I make it so fast?
a few ways:
it's written in python.
it uses eval, one of python's fastest functions
it uses strings, which are faster than numbers (the only number this code relies on is the input one...)
it makes use of the little-known "\" operator, which is one of the fastest operators in python
188
Upvotes
View all comments
Show parent comment
90
u/GlueDonkey Apr 19 '21
it relies on the fact that an odd number of backslashes in a string results in a SyntaxError
"\" <-- the backslash escapes the closing quote which essentially just turns the line into a single quote and nothing else, causing an error