1
import networkx as nx #@UnresolvedImport
from networkx.algorithms import bipartite #@UnresolvedImport
from operator import itemgetter
from random import choice

corpus = open('/home/abehl/Desktop/Corpus/songs.wx', 'r')

ALPHA = 1.5
EPSILON = 0.5

song_nodes = []
word_nodes = []    

edges = zip(song_nodes, word_nodes)

B = nx.Graph(edges)
degX,degY = bipartite.degrees(B, word_nodes)

sortedSongNodesByDegree = sorted(degX.iteritems(), key=itemgetter(1))
print sortedSongNodesByDegree

song_nodes2 = []
word_nodes2 = []
Vc = list(set(word_nodes))

edges2 = zip(song_nodes2, word_nodes2)
C= nx.Graph(edges2)

for songDegreeTuple in sortedSongNodesByDegree:
    for i in range(songDegreeTuple[1]):
        connectedNodes = C.neighbors(songDegreeTuple[0])
        VcDash = [element for element in Vc if element not in connectedNodes]
        calculateBestNode(VcDash)

def calculateBestNode(VcDashsR):
    nodeToProbailityDict = {}
    for node in VcDashsR:
        degreeOfNode = bipartite(C, [node])[1][node]
        probabiltyForNode = (degreeOfNode ** ALPHA) + EPSILON
        nodeToProbailityDict[node] = probabiltyForNode

In the above python program, python interpreter is throwing the following error even though the function 'calculateBestNode' is defined in the program. Am I missing something here.

NameError: name 'calculateBestNode' is not defined

Pardon me for posting a large program here.

4
  • I don't see a calculateSelectedNode function Commented Jun 29, 2011 at 20:32
  • calculateSelectedNode isn't anywhere in your program Commented Jun 29, 2011 at 20:32
  • I have updated the error message, had posted the wrong one here. Commented Jun 29, 2011 at 20:34
  • 3
    You call it before you declare it. Commented Jun 29, 2011 at 20:34

2 Answers 2

8

A Python program is executed from top to bottom, so you need to define the function before you use it. A common alternative is putting all the code that is automatically executed in a main function, and adding at the bottom of the file:

if __name__ == '__main__':
    main()

This has the additional advantage that you have now written a module that can be imported by others.

Sign up to request clarification or add additional context in comments.

1 Comment

The parsing isn't relevant: the entire module is parsed before any of it is executed. What is relevant is that in Python functions are created when the def is executed in the normal flow of the program.
3

You try to use the function calculateBestNode() before you define it in your program. So the interpreter doesn't know it exists.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.