views:

91

answers:

1

Since I'm pretty new this question'll certainly sound stupid but I have no idea about how to approach this.

I'm trying take a list of nodes and for each of the nodes I want to create an array of predecessors and successors in the ordered array of all nodes.

Currently my code looks like this:

    nodes = self.peers.keys()
    nodes.sort()

    peers = {}
    numPeers = len(nodes)
    for i in nodes:
        peers[i] = [self.coordinator]
    for i in range(0,len(nodes)):
        peers[nodes[i%numPeers]].append(nodes[(i+1)%numPeers])
        peers[nodes[(i+1)%numPeers]].append(nodes[i%numPeers])
#        peers[nodes[i%numPeers]].append(nodes[(i+4)%numPeers])
#        peers[nodes[(i+4)%numPeers]].append(nodes[i%numPeers])

The last two lines should later be used to create a skip graph, but that's not really important. The problem is that it doesn't really work reliably, sometimes a predecessor or a successor is skipped, and instead the next one is used, and so forth. Is this correct at all or is there a better way to do this? Basically I need to get the array indices with certain offsets from each other.

Any ideas?

+2  A: 

I would almost bet that when the error occurs, the values in nodes have duplicates, which would cause your dictionary in peers to get mixed up. Your code assumes the values in nodes are unique.

Brenda Holloway
Good point,I'll run it through a filter.
cdecker
Seems to work fine. Strange I always thought that keys would return a list without duplicates.I'll check it with the skip graph and see if that works too :-)
cdecker
It will. You can't have duplicate keys in a dictionary.
Glenn Maynard
Yes, I agree with Glenn. Your nodes should all be unique because they are keys from a dictionary.
Justin Peel
Strange enough, it works like a charm after sorting and removing duplicates :-)
cdecker
I was playing with some code and came up with this, too (I don't know how to format comments with code):nodes = self.peers.keys()nodes.sort()dnodes = nodes + nodespeers = {}for i in range(1,len(nodes)+1): n = dnodes[i] peers[n] = [self.coordinator, dnodes[i-1], dnodes[i+1]]
Brenda Holloway
Ugh, something swallowed the comment I had written :PI said (as Glenn and Justin) that, on the code you pasted, "nodes" will only have unique elements, since dictionary keys are unique by definition. Before trying to "remove duplicates", check if there actually are any. If there are, there's something *very* wrong with your code (or your Python) :POn a previous comment, you mention an "array of nodes". If *that* has duplicate entries, then those will be lost as soon as you use them as dictionary keys. The discrepancies will then follow.
rbp
I wanted to share the resulting network graph, which thanks to your help now works perfectly :Dhttp://bit.ly/aV1tOtThank you very much :)
cdecker