I have the following code that runs breadth first search (bfs) on a list of graph vertices.
Currently I have code that is running bfs on every item in the list, but I want to make it so that if the next item in the for loop is already in the set of discovered nodes, then the for loop should skip over it, so that bfs does not have to be performed on every vertex.
My main reason for doing this is because I have to read in a very large file, so it causes a memory crash when I perform bfs on every vertex; my code works on small test cases but not on the large file.
I know the continue statement allows you to skip over the current iteration, but I can't figure how to skip the next iteration.
Any help is appreciated; thank you.
def count_components(g):
dictionary = {}
dict_list = {}
for i in g.vertices():
dictionary = breadth_first_search(g,i)
dictionary_keys = list(dictionary.keys())
dict_list[i] = dictionary_keys
for value in dict_list.values():
for i in range(len(value)):
value[i] = str(value[i])
result = {}
for key, value in dict_list.items():
dict_list[key].sort(key=str.lower)
if value not in result.values():
result[key] = value
count = len(result)
return count
The continue statement (with or without a label reference) can only be used to skip one loop iteration. The break statement, without a label reference, can only be used to jump out of a loop or a switch.
The break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break found in C. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.
Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.
Two options, which you pick is up to you:
1) Start your loop with a guard clause. This lets you call continue
and skip that iteration of the loop.
>>> values = [0,1,2,1,0]
>>> known = set([2])
>>> for i in values:
... if i in known:
... continue
... print i
... known.add(i)
...
0
1
2) Use a generator in the for statement:
>>> values = [0,1,2,1,0]
>>> known = set([2])
>>> for i in (x for x in values if not x in known):
... print i
... known.add(i)
...
0
1
Which is best is up to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With