Reputation: 819
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
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
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