Archive for August, 2010

Prime numbers and Numpy – Python

Friday, August 27th, 2010

I've been looking at the element-wise operations in Numpy arrays. The code below generates 100K primes in about 1.3 secs on my laptop. [sourcecode language="python"] import numpy import math def prime(upto=100): return filter(lambda num: (num % numpy.arange(2,1+int(math.sqrt(num)))).all(), range(2,upto+1)) [/sourcecode] >>> prime() [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, ...

Birthday Simulations – Python

Thursday, August 26th, 2010

I've wanted for a while to write simple python simulations of the birthday puzzles I'd written about previously. Then, recently, I was wondering what the most efficient way to tell if a list has duplicate elements. It suddenly dawned on me that these two topics were related: The ...

Shortest Path – Python

Tuesday, August 24th, 2010

Problem: Write a python function to calculate the shortest path given a start node (or vertex), an end node and a graph. Use Dijkstra's algorithm. Return the distance from the start node to the end node, as well as the path taken to get there. The implementation ...