Advertisement
Vermiculus

q1

Mar 20th, 2012
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. def d(s):
  2.     raw_input("----DEBUG----{0}".format(s))
  3.  
  4. class City:
  5.     # parses the intersections from a string s
  6.     def __init__(self, s):
  7.         nums = s.split()
  8.         self.juncs = set(map(int,nums))
  9.        
  10.         self.roads = dict()
  11.        
  12.         for i in range(0, len(nums), 2):
  13.             if int(nums[i]) in self.roads:
  14.                 self.roads[int(nums[i])].append(int(nums[i+1]))
  15.             else:
  16.                 self.roads[int(nums[i])] = [int(nums[i+1])]
  17.    
  18.     def paths(self, a, b, current_path=[]):
  19.         # IF
  20.         #   the start point and end point are the same at the beginning,
  21.         #   junction 'a' does not exist
  22.         #   junction 'b' does not exist
  23.         #   there are not outgoing roads from 'a'
  24.         # return nothing
  25.         if (current_path == [] and a == b) or a not in self.juncs or b not in self.juncs or not self.roads.has_key(a):
  26.             return []
  27.        
  28.         # add the starting junction to the path
  29.         current_path = current_path + [a]
  30.        
  31.         # If we've reached the endpoint,
  32.         if a == b:
  33.             return [current_path]
  34.        
  35.         # prepare the return
  36.         thispath = []
  37.        
  38.         # for every junction reachable from a
  39.         for junction in self.roads[a]:
  40.             # if we haven't already visited this junction,
  41.             if junction not in current_path:
  42.                 # send out a probe finding all paths from this junction to the ending point
  43.                 probe = self.paths(junction, b, current_path)
  44.                 # add all the paths found
  45.                 for potential_path in probe:
  46.                     thispath.append(potential_path)
  47.        
  48.         # return the paths found from junction a to junction b
  49.         return thispath
  50.  
  51. # takes an input string and returns a list of Cities
  52. def parse(s):
  53.     print "p"
  54.  
  55. t =  City("0 1  0 2  0 4  2 4  2 3  3 1  4 3")
  56.  
  57. print t.paths(0,3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement