views:

238

answers:

1

Using Python's Networkx library, I created an undirected graph to represent a relationship network between various people. A snippet of my code is below:

import networkx as nx
    def creategraph(filepath):
    G=nx.Graph()
    #All the various nodes and edges are added in this stretch of code.
    return G

From what I understand, each node is basically a dictionary. The problem that this presents to me is that I want to perform a different kind of Random Walk algorithm. Now before you jump on me and tell me to use one of the standard functions of the Networkx library, I want to point out that it is a custom algorithm. Suppose I run the creategraph function, and the G object is returned and stored in another object (let's call it X). I want to start off at a node called 'Bob.' Bob is connected to Alice and Joe. Now, I want to reassign Y to point to either Alice or Bob at random (with the data I'm dealing with, a given node could have hundreds of edges leaving it). How do I go about doing this? Also, how do I deal with unicode entries in a given node's dict (like how Alice and Joe are listed below?)

X = creategraph("filename")
Y=X['Bob']
print Y
>> {u'Alice': {}, u'Joe': {}}
+2  A: 

The choice function in the random module could help with the selection process. You don't really need to worry about the distinction between unicode and string unless you're trying to write them out somewhere as sometimes unicode characters aren't translatable into the ASCII charset that Python defaults to.

The way you'd use random.choice would be something along the lines of:

Y = Y[random.choice(Y.keys())]
Benno
Thanks, Benno. Your answer was very helpful in solving my problem.
rohanbk