HNHacker News
TopNewBestAskShowJobs

daivd

641 karma · joined October 21, 2009

submissionscomments
daivd··on Python vs Clojure 2: Reloaded
Making it shorter is trivial :) I have never tried posting code here, so I I'll try to get the formatting right.

  #The import line is unnecessary. It can be inlined, like so:
  def is_prime(i): return (i > 1 and all(i % x != 0 for x in range(2, int(__import__('math').sqrt(i)) + 1)))

  #Mersenne prime can be put on one line with some functional beautification:
  def is_mersenne_prime(p): return p == 2 or not reduce(lambda x, y: (x ** 2 - 2) % (( 1 << p ) - 1), range(3, p + 1), 4)

  #With a list comprehension we do not need "if ..:" and can put the loop on one line as well:
  for p in [range(2,33219) if s_prime(p) and is_mersenne_prime(p)]: print("M%d"%p)

Three lines. Of course the functions are unnecessary, so inline them in the for-loop and we have our magic target, one line!

I have replaced the list comprehension and range with generators, so if you run this one-liner in your python terminal you will get a continuous stream of primes (if it flushes the prints properly).

  for q in (p for p in xrange(2,33219) if (p > 1 and all(p % x != 0 for x in range(2, int(__import__('math').sqrt(p)) + 1))) and (p == 2 or not reduce(lambda x, y: (x ** 2 -2) % (( 1 << p ) - 1), range(3, p + 1), 4))): print("M%d"%q)
Easy as pie.

I don't know anything about code golf, so perhaps I am breaking some rule with the longer than 80 char line? Using ; to sequence statements as in the original is definitely cheating, IMHO :)

← PreviousPage 3 of 3