Created
January 3, 2014 23:13
-
-
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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