The best solution I've found so far for a golf code puzzle I'm working on includes two rather fat-looking invocations of
range. I'm very new at code golf, especially in Python, so I could use a few tips.
The relevant fragment is this
[x for x in range(n+1,7**6)if`x`==`x`[::-1]*all(x%i for i in range(2,x))]
The upper limit of the first
range is not a sharp one. It should be at least 98690, and all else being equal (golf-wise, that is), the smaller the difference between this upper limit and 98690 the better, performance-wise1. I'm using 76 (=117649) because
7**6 is the shortest Python expression I can come up with that fits the bill.
In contrast, the lower limit in the first
range, as well as both limits in the second one, are firm. IOW, the program (in its current form) will produce incorrect results if those limits are changed.
Is there a way to shorten one or both of the expressions
BTW, in this case, aliasing
range to, say,
r gains nothing:
EDIT: FWIW, the full program is this:
p=lambda n:[x for x in range(n+1,7**6)if`x`==`x`[::-1]*all(x%i for i in range(2,x))]
p(n) should be the smallest palindromic prime greater than
p should not be recursive. Warning: It is already obscenely slow!
1Yes, I know: performance is irrelevant in code golf, but that's why I wrote "all else being equal (golf-wise, that is)". For example, my choice of
7**6, and not the more immediately obvious, but poorer-performing, "golf-equivalent" alternative
9**9. I like to actually run my code golf attempts, which means not letting the performance degrade to the point that it would take years to run the code. If I can help it, of course.
p=lambda n:(x for x in xrange(n+1,7**6)if`x`==`x`[::-1]*all(x%i for i in xrange(2,x))).next(). Of course, while your at that, might as well change
xrange(2,int(x**.5+1))and make your testing really fast. Clearly this code is equivalent to yours, just longer and faster. \$\endgroup\$