http://projecteuler.net/problem=83

I used the pseudocode from Wikipedia on Dijkstra’s algorithm to solve this problem.

# euler 82
# grid is a dictionary with key as tuple (i,j) and value as value of node
# i is row, j is column of grid

import time
t0 = time.time()

f = open('matrix.txt', 'r')
grid = {}
counter = 1
for line in f:
   temp = line.replace('\n','')
   temp = temp.split(',')
   for a in range(len(temp)):
       grid[(counter,a+1)] = int(temp[a])
   counter += 1
rows = 80
cols = 80

def findNeighbors(vertex):
   i, j = vertex[0], vertex[1]
   output = [(i-1,j), (i+1,j), (i,j-1), (i,j+1)]  # all neighbors
   remove = []
   for v in output:
      if v[0] < 1 or v[0] > rows or v[1] < 1 or v[1] > cols:
         remove.append(v)
   final = [x for x in output if not x in remove]
   return final

# Let's implement Dijkstra's algo from Wikipedia
def dka(graph, source):    # graph will be our grid, source will be (1,1)
   dist = {}
   for v in graph:
      dist[v] = float("inf")
   dist[source] = graph[source]
   Q = dist.copy()   #make a copy of graph, as a hash
   length = len(Q)
   while length > 0:
      u = min(Q, key=Q.get)
      if dist[u] == float("inf"):
         break
      if u == (rows, cols):
         break
      del Q[u]
      length -= 1
      n = findNeighbors((u))
      neighbors = [x for x in n if x in Q]
      for v in neighbors:
         alt = dist[u] + grid[v]
         if alt < dist[v]:
            dist[v] = alt
            Q[v] = alt
   return dist

answerGrid = dka(grid,(1,1))

print "The answer is ", answerGrid[(rows,cols)]
t1= time.time()
total = t1-t0
print total, "seconds"

{ 0 comments }

From StackOverflow:

http://stackoverflow.com/questions/3282823/python-get-key-with-the-least-value-from-a-dictionary

min(d, key=d.get)

{ 0 comments }

Project Euler 82 – Find the minimal path sum from the left column to the right column

January 27, 2012

http://projecteuler.net/problem=82 I’m looking forward to reading the forums in Euler for this one, as I’m curious to find a more elegant way to solve this problem… # euler 82 f = open(‘matrix.txt’, ‘r’) # grid is a dictionary with key as tuple (i,j) and value as value of node # i is row, j is [...]

Read the full article →

If I’m using a for loop to generate a list of strings, how do I create a list of the variables, and not a list of the strings?

January 26, 2012

I posed a question on StackExchange today…. http://stackoverflow.com/q/9020500/1171561

Read the full article →

Project Euler 79 – By analysing a user’s login attempts, find the secret passcode

January 24, 2012

http://projecteuler.net/problem=79 As I was researching the web for approaches to solving this problem, I found Kristian’s MathBlog article quite useful (as usual), and so I took up his suggestion to try implementing a topological sorting algorithm, which I found described in Wikipedia. I had some problems just using the pseudocode described in Wikipedia, mostly because [...]

Read the full article →

Thou Shalt Not Modify A List During Iteration

January 24, 2012

Some good coding tips from this blog….. http://unspecified.wordpress.com/2009/02/12/thou-shalt-not-modify-a-list-during-iteration/

Read the full article →

Project Euler 134 – Investigating consecutive primes and the Extended Euclidean Algorithm

January 22, 2012

http://projecteuler.net/problem=134 My code took 2.5 seconds. In order to optimize this code, I had to use the Extended Euclidean Algorithm that I read about in Wikipedia. Brute force won’t work, so this optimization speeds up the code substantially. In essence, you are solving for a linear congruence of the form ax = b mod n. [...]

Read the full article →

Project Euler 98 – Investigating words and anagrams that are square numbers

January 20, 2012

http://projecteuler.net/problem=98 A very hacky solution, I admit, but I got it to work. #euler 98 import time import math t0 = time.time() f = open(‘words.txt’, ‘r’) for line in f: a = line.split(‘,’) maxLength = 0 for i in range(len(a)): a[i] = a[i].strip(‘”‘) if len(a[i]) > maxLength: maxLength = len(a[i]) print “longest word has “, [...]

Read the full article →

Project Euler 101 – Building polynomial functions based on first k terms of a sequence

January 17, 2012

http://projecteuler.net/problem=101 #euler 101 # let’s use numpy for our linear algebra matrix operations import math from numpy import * # we’ll use the array data structure for vectors, matrix # multiplication, and inverses #tenth polynomial generating function (and the test cube function) def polyTerm(n): return int(1 – n + n*n – math.pow(n,3) + math.pow(n,4) – [...]

Read the full article →

Project Euler 102 notes – Triangle interiors

January 12, 2012

While I coded up my solution to Project Euler 102 using the article I read on Wolfram Alpha, I was trying to derive the steps they took to solve for a, b in the article – and I found it much more intuitive to just get to a, b by simply inverting the 2 x [...]

Read the full article →