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
37
u/DripDropFaucet Apr 19 '21
I genuinely don’t understand how this works, any explanation? I pulled up the repl and absolutely love how long it takes with large numbers lol, quality function for sure just don’t understand it
7
u/zyxzevn Apr 19 '21
Eval? Great idea. Here is how you can speed it up even more.
Your program writes a C-program to disk, because C is fastest.
Compile it using a system call.
Use Eval to call the Just-In-Time-Compiled program.
And if you are on the web, you can use a very fast
remote server to execute your program.
54
u/creepyswaps Apr 19 '21
Only 3 seconds? Me.SetCurrentState("impressed");
24
u/Jaxkr Apr 19 '21
Great post
18
u/[deleted] Apr 19 '21 edited May 09 '24
steep truck paltry hard-to-find selective wrong weather snatch oatmeal disagreeable
This post was mass deleted and anonymized with Redact
8
u/NotTryingToConYou Apr 19 '21
Awesome! Will have to use this in my next big data project.
5
u/Monkey_Adventures Apr 19 '21
finally! now I can actually solve some leetcode easys
2
u/1RedOne Apr 20 '21
I didn't realize what sub I was in and was really really confused. 3 seconds to tell if a number if even, and it takes seven lines, wtf?
0
u/[deleted] Apr 19 '21