Skip to content

Instantly share code, notes, and snippets.

@prat0318
Created January 3, 2014 23:13
Show Gist options
  • Save prat0318/8248546 to your computer and use it in GitHub Desktop.
Save prat0318/8248546 to your computer and use it in GitHub Desktop.
Imagine you are given a network of nodes. Node objects contain no extra data except a list of neighbor nodes to which they are connected. Your goal is to write a copy function that will duplicate the entire structure of a graph that has already been instantiated in memory. The function takes a single starting node as input and outputs a complete…
class Node:
def __init__(self, nbrs):
self.nbrs = nbrs
def add_nbr(self, node_nbr):
self.nbrs.append(node_nbr)
def copy(self):
return self.copy_recurse({})
def copy_recurse(self, hash):
if self in hash: return hash[self]
node_return = Node([])
hash[self] = node_return
for i in self.nbrs:
node_return.add_nbr(i.copy_recurse(hash))
return node_return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment