guddu
guddu

Reputation: 165

How to skip the next iteration during a for loop in python?

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

Upvotes: 15

Views: 45210

Answers (1)

Baldrickk
Baldrickk

Reputation: 4409

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
  1. 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 x not in known):
...     print(i)
...     known.add(i)
...
0
1

Which is best is up to you.

Upvotes: 26

Related Questions