0

I am trying to implement a dfs to find cycles in a string graph. For example the graph:

walkways_info = """\
U 3
0 1
1 2
2 0
"""

Would return True. I am currently having the issue that my if statement:

if current_vertex in visited or int(graph[i].split()[1]) in visited:

It is outputting False but I don't want it to output anything at this stage.

Updated code Here

I'd appreciate some help.

T. Kearsley
  • 197
  • 3
  • 18
  • 2
    I would propose to you building an adjacency matrix based on string representation BEFORE solving any graph-based task. This way you will be able to use well-known and polished algorithms and implementation. – CaptainTrunky Mar 22 '17 at 02:33
  • Look at your code: the only way it can return `False` is when your graph is empty! – Julien Mar 22 '17 at 02:42
  • I've added `return False` outside of the for loop shouldn't this trigger if the graph is iterated through and `return True` isn't called? – T. Kearsley Mar 22 '17 at 02:56
  • I added a print statement at `else: return True` `print(visited)` and visited is a empty list. It must not be entering the `if current_vertex in visited == False` loop but I'm not sure why.. – T. Kearsley Mar 22 '17 at 02:59
  • Bump.................. – T. Kearsley Mar 22 '17 at 03:33
  • Sufficient code to allow a question to be answered needs to be included **in the question itself** to comply with MCVE rules. Links bitrot. – Charles Duffy Mar 22 '17 at 13:24

1 Answers1

0

I believe that you have an order of operation error, the in and == are not playing nicely.

current_vertex in visited == True evaluates like this (current_vertex in (visited == True))

Example:

In [1]: x = [0,1,2]

In [2]: y = 1

In [3]: y in x == True
Out[3]: False

In [3]: y in x
Out[3]: True

So if you drop your == True it should work.

if current_vertex in visited or int(graph[i].split()[1]) in visited:
miah
  • 10,093
  • 3
  • 21
  • 32
  • Hey Thanks for this but I noticed now when it gets to `if current_vertex in visited or int(graph[i].split()[1]) in visited` it will output `False` can I get it to not do this? – T. Kearsley Mar 22 '17 at 04:06