Skip to content

Commit 6eb5e62

Browse files
committed
fix mistake usage of self param in recursive func and [] as default param
1 parent 8300928 commit 6eb5e62

File tree

1 file changed

+16
-16
lines changed

1 file changed

+16
-16
lines changed

graph_search.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ class GraphSearch:
1010
def __init__(self, graph):
1111
self.graph = graph
1212

13-
def find_path(self, start, end, path=[]):
13+
def find_path(self, start, end, path=None):
1414
self.start = start
1515
self.end = end
16-
self.path = path
16+
self.path = path if path else []
1717

1818
self.path += [self.start]
1919
if self.start == self.end:
@@ -27,37 +27,37 @@ def find_path(self, start, end, path=[]):
2727
return newpath
2828
return None
2929

30-
def find_all_path(self, start, end, path=[]):
30+
def find_all_path(self, start, end, path=None):
3131
self.start = start
3232
self.end = end
33-
self.path = path
34-
self.path += [self.start]
33+
_path = path if path else []
34+
_path += [self.start]
3535
if self.start == self.end:
36-
return [self.path]
36+
return [_path]
3737
if self.start not in self.graph:
3838
return []
3939
paths = []
4040
for node in self.graph[self.start]:
41-
if node not in self.path:
42-
newpaths = self.find_all_path(node, self.end, self.path)
41+
if node not in _path:
42+
newpaths = self.find_all_path(node, self.end, _path[:])
4343
for newpath in newpaths:
4444
paths.append(newpath)
4545
return paths
4646

47-
def find_shortest_path(self, start, end, path=[]):
47+
def find_shortest_path(self, start, end, path=None):
4848
self.start = start
4949
self.end = end
50-
self.path = path
50+
_path = path if path else []
5151

52-
self.path += [self.start]
52+
_path += [self.start]
5353
if self.start == self.end:
54-
return self.path
54+
return _path
5555
if self.start not in self.graph:
5656
return None
5757
shortest = None
5858
for node in self.graph[self.start]:
59-
if node not in self.path:
60-
newpath = self.find_shortest_path(node, self.end, self.path)
59+
if node not in _path:
60+
newpath = self.find_shortest_path(node, self.end, _path[:])
6161
if newpath:
6262
if not shortest or len(newpath) < len(shortest):
6363
shortest = newpath
@@ -82,5 +82,5 @@ def find_shortest_path(self, start, end, path=[]):
8282

8383
### OUTPUT ###
8484
# ['A', 'B', 'C', 'D']
85-
# [['A', 'B', 'C', 'D']]
86-
# ['A', 'B', 'C', 'D']
85+
# [['A', 'B', 'C', 'D'], ['A', 'B', 'D'], ['A', 'C', 'D']]
86+
# ['A', 'B', 'D']

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy