Reputation: 19
checking for an element in a graph with using with using depth first search. Why always return "True"?
graph1 = {1: [2, 7, 8],
2: [3, 6],
3: [4, 5],
4: [],
5: [],
6: [],
7: [],
8: [9, 12],
9: [10],
10: [],
11: [],
12: []}
element = int(input("Введите значение "))
def search(graph, node):
if node == element:
return True
else:
for n in graph[node]:
search(graph, n)
return False
print(search(graph1, element))
Upvotes: 0
Views: 157
Reputation: 1205
element = int(input("Введите значение "))
Here you assign to element the value you wish to find using depth-first.
You call the search function like this:
print(search(graph1, element))
And in the function, you start with:
def search(graph, node):
if node == **element**:
...
element
and node
are the same values therefore always returning true when compared.
Upvotes: 1
Reputation: 8811
Thats because as soon at is entering the function, it is checking the value of node
and element
and since you have called the function using element
as parameter value for node
, this condition will always be true.
Upvotes: 1