12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

print y, 'not prime'else:x = y // 2while x > 1:if y % x == 0:print y, 'has factor', xbreakx -= 1else:print y, 'is prime'# Future / fails# No remainder?# Skip elseprime(13); prime(13.0)prime(15); prime(15.0)prime(3); prime(2)prime(1); prime(-3)Here is the module in action; the // operator allows it to works for floating-pointnumbers too, even though it perhaps should not.% python primes.py13 is prime13.0 is prime15 has factor 515.0 has factor 5.03 is prime2 is prime1 not prime-3 not primeThis function still isn’t very reusable, yet—it could return values, instead ofprinting—but it’s enough to run experiments. It’s also not a strict mathematicalprime (floating-points work), and is still inefficient. Improvements are left asexercises for more mathematically minded readers. Hint: a for loop overrange(y, 1, -1) may be a bit quicker than the while (in fact, it’s roughly twice asfast in 2.2), but the algorithm is the real bottleneck here. To time alternatives,use the built-in time module and coding patterns like those used in this generalfunction-call timer (see the library manual for details):def timer(reps, func, *args):import timestart = time.clock( )for i in xrange(reps):apply(func, args)return time.clock( ) - start9. List comprehensions. Here is the sort of code you should write; I may have a preference,but I’m not telling:>>> values = [2, 4, 9, 16, 25]>>> import math>>> res = []>>> for x in values: res.append(math.sqrt(x))...660 | Appendix B: Solutions to End-of-Part Exercises

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!