jukhamil
jukhamil

Reputation: 819

Is there a Python function for this piece of code?

I created a graph by putting nodes in a list. Node is a class with attributes 'parent', 'daughters', and 'edge'. I want to check if a symbol is in the edges of any of the daughter-nodes of a current node, and if so, to change the current node to that node. If not, then I create a new node with that edge, and change the current node to it.

I do this like this:

match = False
for daughter in currentNode.daughters:
    if daughter.edge == currentSymbol:
        match = True
        currentNode = daughter
if match == False:
    trie.append(node(currentNode, [], currentSymbol)
    currentNode = trie[-1]

The use of 'match' seems inelegant to me. Is there a better syntax for checking if the edge exists among the daughters, and if so, updating the current node to that daughter, and if not, creating that node?

Upvotes: 2

Views: 60

Answers (2)

poke
poke

Reputation: 388133

You can use the for...else syntax here:

for daughter in currentNode.daughters:
    if daughter.edge == currentSymbol:
        currentNode = daughter
        break
else:
    trie.append(node(currentNode, [], currentSymbol)
    currentNode = trie[-1]

The else part is executed, only if the for loop completed normally without ever breaking. So in your case, if you find a match, you break from the loop (aborting it), and the else is skipped. And if you don’t find a match, you never break from the loop, and the else is executed.

Upvotes: 3

tobias_k
tobias_k

Reputation: 82929

You can use for/else here:

for daughter in currentNode.daughters:
    if daughter.edge == currentSymbol:
        currentNode = daughter
        break
else:
    trie.append(node(currentNode, [], currentSymbol)
    currentNode = trie[-1]

The else case will be executed if the for loop exited normally, i.e. without break

Upvotes: 4

Related Questions