Rcjp's Weblog

February 25, 2008

K language – ultimate coding brevity?

Filed under: python — rcjp @ 5:56 pm

After reading a thread on c.l.l and, over the last week, more than I care to on arc’s emphasis on brevity, I can’t decide if I’m impressed or appalled by the K language.

As K seems to be a proprietary language I wouldn’t normally look at it, but thankfully the Wikipedia entry has a link to a screencast by Michael Schidlowsky solving the birthday problem – how many people do you need in a room to, more often than not, have two or more persons with the same birthday. In K, to simulate 1000 rooms with 10 people in them its

#+/{~(#x)=#?x}' {(1000,x) _draw 365} 10

using ipython I’d do:

In [1]: from random import randint
In [2]: def samebday(n): return n != len(set(randint(1,365) for i in range(n)))
In [3]: def bday1000(n): return [samebday(n) for i in range(1000)].count(True)
In [4]: bday1000(23)
Out[4]: 496
In [5]: %timeit bday1000(23)
10 loops, best of 3: 367 ms per loop

Casting the list of random ‘birthdays’ (just integers from 1..365) to a python set removes any duplicates, so just checking if the length has changed will show if two or more were the same. The tipping point is 23 according to wikipedia, and the bday1000 function simulating 1000 rooms shows 496 of those rooms had common birthdays – which is roughly half of them. Not as short as K, but concise enough for me I think.


Leave a Comment »

No comments yet.

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: