Monday, January 6, 2014

2014.py :-)

By Vasudev Ram

There was this thread on Hacker News:

Produce the number 2014 without any numbers in your code (stackexchange.com), which in turn came from this question on codegolf.stackexchange.com.

Somewhat silly or at least contrived question, but for fun, using this idea by HN user colomon, I worked out a solution:
import time
s = time.ctime()
print s[s.rindex(' '):].strip()

which outputs:

2014

The solution uses a total of 64 bytes, or 56 without the .strip(), which is only needed to remove a leading space from the output.

[ Update: A suggestion from HN user colomon to get the year directly (see same HN thread), led to this improved version:
import time
print time.localtime()[0]
which brings it down to ~40 bytes. ]

There were shorter solutions in Python at the original question page, and some of the shortest were in Python, Ruby, Go and FORTH.

One nice solution in Python was this :-)
print sum(ord(c) for c in 'Happy new year to you!')
It actually works.

- Vasudev Ram - Dancing Bison Enterprises

Contact Page



5 comments:

Anonymous said...

print sum(map(ord, 'Happy new year to you!'))

Anonymous said...

Except print time.localtime()[0] has a number in it... (Sorry if multiple posts... comment page is messed up and gives no feedback that it worked.)

Vasudev Ram said...

>Except print time.localtime()[0] has a number in it... (Sorry if multiple posts... comment page is messed up and gives no feedback that it worked.)

Oops, missed that - thanks. Then I'd have to use .tm_year instead, as others have done in the HN thread.

Odd about the comments issue. I don't get it - either when I reply to comments on my own posts, or even when I'm the first to comment on my own post, such as to make a correction to the material discussed. I also get proper feedback that it worked, including the option to see a preview before publishing the comment. Maybe it is an issue related to the specific browser you use. I use Chrome on Linux and Windows. Or are you on mobile? That can cause issues, even Disqus has issues with comments on mobile. Mine is Blogger though.

Vasudev Ram said...

Here is another way to do it :-)

# Name this file as 2014.py
import sys, os
s = os.path.basename(sys.argv.pop())
print s[:s.index('.')]

Then run it with the command:

2014.py

Voila!

Vasudev Ram said...

Note to readers: the links to Hacker News threads in the above post, are now corrupted - some point to random other posts, not the ones I originally linked to. The reason for that is that the Hacker News server (news.ycombinator.com) recently crashed and they lost all their data (i.e. posts and comments) for a range of a day or two, and that happened just around the time I wrote this post. So caveat lector.