Hey guys,
Hope you all are doing great. I am back with Some Python Programming tips for
CODE GOLF Challenges.
So, What is CODE GOLF??
As per Wikipedia, it is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code (not to be confused with binary Sizecoding) that implements a certain algorithm.
In simple terms, your goal is to write a code is shortest way, using minimum number of characters to implement a logic in correct way.
You can use any language Java, C++, Python, Perl, Ruby, JavaScript, and anything to write it. But scripting language have a upper-hand over descriptive language as you can write programs in concise way in scripting language like Ruby, Python, etc, while it takes an extra character each time to write the code in Java, C#, etc.
So Preferred code golf languages are GolfScript, Flogscript, Perl, Python, Erlang, Ruby, Haskell, Bash, PHP, Clojure, K, Javascript, Vim and the list go on....
I prefer Python or Python3 myself for code golfing
So we will discuss dome tips as generics for code golf programming in Python:
1. Make the assignments shorter.
CODE GOLF Challenges.
So, What is CODE GOLF??
As per Wikipedia, it is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code (not to be confused with binary Sizecoding) that implements a certain algorithm.
In simple terms, your goal is to write a code is shortest way, using minimum number of characters to implement a logic in correct way.
You can use any language Java, C++, Python, Perl, Ruby, JavaScript, and anything to write it. But scripting language have a upper-hand over descriptive language as you can write programs in concise way in scripting language like Ruby, Python, etc, while it takes an extra character each time to write the code in Java, C#, etc.
So Preferred code golf languages are GolfScript, Flogscript, Perl, Python, Erlang, Ruby, Haskell, Bash, PHP, Clojure, K, Javascript, Vim and the list go on....
I prefer Python or Python3 myself for code golfing
So we will discuss dome tips as generics for code golf programming in Python:
1. Make the assignments shorter.
Use a=b=c=0 instead of a,b,c=0,0,0. Use a,b,c='123' instead of a,b,c='1','2','3'.
2. Tweak the if-else condition.
b=2*a if a<0 else 3*a # proper python b=a<0 and 2*a or 3*a # codegolf1 b=a*(3,2)[a<0] # codegolf2
3. Combine multiple conditionals. Instead of "1<x and x<2".
Use 1<x<2
4. Using a built-in function repeatedly, it might be more space-efficient to give it a
new name, if using different arguments.
r=range
for x in r(10): for y in r(100):print x,y
5. Read only two lines from standard in (without the carriage return) and store then in an array of strings.
r=raw_input a=r(),r()
6. Simulating C's ternary operator (p?a:b)
r=[b,a][p]
Stay tuned for more Tips and Tricks in the next Post!!
Till Then Cheers!!
View comments