I'm trying to solve a similar problem to the one listed here: Python: Combinations of parent-child hierarchy
graph = {}
nodes = [
('top','1a'),
('top','1a1'),
('top','1b'),
('top','1c'),
('1a','2a'),
('1b','2b'),
('1c','2c'),
('2a','3a'),
('2c','3c'),
('3c','4c')
]
for parent,child in nodes:
graph.setdefault(parent,[]).append(child)
def find_all_paths(graph, start, path=[]):
path = path + [start]
if not graph.has_key(start):
return path
paths = []
for node in graph[start]:
paths.append(find_all_paths(graph, node, path))
return paths
test = find_all_paths(graph, 'top')
Desired Output:
[['top', '1a', '2a', '3a'],
['top', '1a1'],
['top', '1b', '2b'],
['top', '1c', '2c', '3c', '4c']]
Actual Output:
[[[['top', '1a', '2a', '3a']]],
['top', '1a1'],
[['top', '1b', '2b']],
[[[['top', '1c', '2c', '3c', '4c']]]]]
Any advice on how I can remove the extra nesting? Thanks!
The following should fix your issue:
def find_all_paths(graph, start, path=None):
if path is None:
# best practice, avoid using [] or {} as
# default parameters as #TigerhawkT3
# pointed out.
path = []
path = path + [start]
if not graph.has_key(start):
return [path] # return the path as a list of lists!
paths = []
for node in graph[start]:
# And now use `extend` to make sure your response
# also ends up as a list of lists
paths.extend(find_all_paths(graph, node, path))
return paths
The issue is confusion between path which is a single list, and paths, which is a list of lists. Your function can return either one, depending on where you are in the graph.
You probably want to return a list of paths in all situations. So change return path in the base case to return [path].
In the recursive case, you now need to deal with merging each child's paths together. I suggest using paths.extend(...) instead of paths.append(...).
Putting that all together, you get:
def find_all_paths(graph, start, path=[]):
path = path + [start]
if not graph.has_key(start):
return [path]
paths = []
for node in graph[start]:
paths.extend(find_all_paths(graph, node, path))
return paths
Here's a non-recursive solution. However, it "cheats" by sorting the output lists.
def find_all_paths(edges):
graph = {}
for u, v in edges:
if u in graph:
graph[v] = graph[u] + [v]
del graph[u]
else:
graph[v] = [u, v]
return sorted(graph.values())
data = (
('top','1a'),
('top','1a1'),
('top','1b'),
('top','1c'),
('1a','2a'),
('1b','2b'),
('1c','2c'),
('2a','3a'),
('2c','3c'),
('3c','4c'),
)
test = find_all_paths(data)
for row in test:
print(row)
output
['top', '1a', '2a', '3a']
['top', '1a1']
['top', '1b', '2b']
['top', '1c', '2c', '3c', '4c']
Related
how can I find all possible path between two nodes in a graph using networks?
import networkx as nx
G = nx.Graph()
edges = ['start-A', 'start-b', 'A-c', 'A-b', 'b-d', 'A-end', 'b-end']
nodes = []
for node in edges:
n1 = node.split('-')[0]
n2 = node.split('-')[1]
if n1 not in nodes:
nodes.append(n1)
if n2 not in nodes:
nodes.append(n2)
for node in nodes:
G.add_node(node)
for edge in edges:
n1 = edge.split('-')[0]
n2 = edge.split('-')[1]
G.add_edge(n1, n2)
for path in nx.all_simple_paths(G, 'start', 'end'):
print(path)
This is the result:
['start', 'A', 'b', 'end']
['start', 'A', 'end']
['start', 'b', 'A', 'end']
['start', 'b', 'end']
But I want all possible path so for e.g. start,b,A,c,A,end
If repeated visits to a node are allowed, then in a graph where at least 2 nodes on the path (not counting start and end) are connected, there is no upper bound to the number of valid paths. If there are 2 nodes on the path that are connected, e.g. nodes A and B, then any number of new paths can be formed by inserting A->B->A into the appropriate section of the valid path between start and end.
If number of repeated visits is restricted, then one might take the all_simple_paths as a starting point and insert any valid paths between two nodes in between, repeating this multiple times depending on the number of repeated visits allowed.
In your example, this would be taking the third output of all_simple_paths(G, 'start', 'end'), i.e. ['start', 'b', 'A', 'end'] and then for all nodes connected to b iterate over the results of all_simple_paths(G, X, 'A'), where X is the iterated node.
Here's rough pseudocode (it won't work but suggests an algo):
for path in nx.all_simple_paths(G, 'start', 'end'):
print(path)
for n, X, Y in enumerate(zip(path, path[1:])):
if X is not 'start' and X is not 'end':
for sub_path in nx.all_simple_paths(G, X, Y):
print(path[:n] + sub_path + path[n+2:])
This is not great, since with this formulation it's hard to control the number of repeated visits. One way to fix that is to create an additional filter based on the counts of nodes. However, for any real-world graphs this is not going to be computationally feasible due to the very large number of paths and nodes...
I am new to python and algorithms. I have been trying to implement a topological sorting algorithm for a while but can't seem to create a structure that works. The functions I have made run on a graph represented in an adj list.
When I have a DFS, the nodes are discovered top down, and nodes that have been already visited and not processed again:
def DFS(location, graph, visited = None):
if visited == None:
visited = [False for i in range(len(graph))]
if visited[location] == True:
return
visited[location] = True
node_visited.append(location)
for node in graph[location]:
DFS(node, graph, visited)
return visited
When I am trying to build a topological sort algorithm, I create a new function which essentially checks the "availability" of that node to be added to the sorted list (ie: whether its neighbouring nodes have been visited already)
def availability(graph, node):
count = 0
for neighbour in graph[node]:
if neighbour in available_nodes:
count += 1
if count != 0:
return False
return True
However, my issue is that once I have visited the node path to get to the bottom of the graph, the DFS does not allow me to revisit that those nodes. Hence, any updates I make once I discover the end of the path can not be processed.
My approach may be totally off, but I am wondering if someone could help improve my implementation design, or explain how the implementation is commonly done. Thanks in advance.
You don't need that availability check to do a topological sort with DFS.
DFS itself ensures that you don't leave a node until its children have already been processed, so if you add each node to a list when DFS finishes with it, they will be added in (reverse) topological order.
Don't forget to do the whole graph, though, like this:
def toposort(graph):
visited = [False for i in range(len(graph))]
result = []
def DFS(node):
if visited[node]:
return
visited[node] = True
for adj in graph[node]:
DFS(adj)
result.append(node)
for i in range(len(graph)):
DFS(i)
return result
class Graph:
def __init__(self):
self.edges = {}
def addNode(self, node):
self.edges[node] = []
def addEdge(self, node1, node2):
self.edges[node1] += [node2]
def getSub(self, node):
return self.edges[node]
def DFSrecu(self, start, path):
for node in self.getSub(start):
if node not in path:
path = self.DFSrecu(node, path)
if start not in path:
path += [start]
return path
def topological_sort(self, start):
topo_ordering_list = self.DFSrecu(start, [])
# this for loop it will help you to visit all nodes in the graph if you chose arbitrary node
# because you need to check if all nodes in the graph is visited and sort them
for node in g.edges:
if node not in topo_ordering_list:
topo_ordering_list = g.DFSrecu(node, topo_ordering_list)
return topo_ordering_list
if __name__ == "__main__":
g = Graph()
for node in ['S', 'B', 'A', 'C', 'G', 'I', "L", 'D', 'H']:
g.addNode(node)
g.addEdge("S", "A")
g.addEdge("S", "B")
g.addEdge("B", "D")
g.addEdge("D", "H")
g.addEdge("D", "G")
g.addEdge("H", "I")
g.addEdge("I", "L")
g.addEdge("G", "I")
last_path1 = g.topological_sort("D")
last_path2 = g.topological_sort("S")
print("Start From D: ",last_path1)
print("start From S: ",last_path2)
Output:
Start From D: ['L', 'I', 'H', 'G', 'D', 'A', 'B', 'S', 'C']
start From S: ['A', 'L', 'I', 'H', 'G', 'D', 'B', 'S', 'C']
you can see here 'C' is included in topological sorted list even it's not connect to any other node but 'C' in the graph and you need to visited her
that's way you need for loop in topological_sort() function
s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
for line in gfile.split():
nodes = line.split(":")[1].replace(';',',').split(',')
for node in nodes:
print node
print read_nodes(s)
I am expected to get ['A','B','C','D','E',.....'N'], but I get A B C D E .....N and it's not a list. I spent a lot of time debugging, but could not find the right way.
I believe this is what you're looking for:
s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
nodes = [line.split(":")[1].replace(';',',').split(',') for line in gfile.split()]
nodes = [n for l in nodes for n in l]
return nodes
print read_nodes(s) # prints: ['A','B','C','D','E',.....'N']
What you were doing wrong is that for each sub-list you create, your were iterating over that sub-list and printing out the contents.
The code above uses list comprehension to first iterate over the gfile and create a list of lists. The list is then flattened with the second line. Afterwards, the flatten list is returned.
If you still want to do it your way, Then you need a local variable to store the contents of each sub-list in, and then return that variable:
s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
all_nodes = []
for line in gfile.split():
nodes = line.split(":")[1].replace(';',',').split(',')
all_nodes.extend(nodes)
return all_nodes
print read_nodes(s)
Each line you read will create a new list called nodes. You need to create a list outside this loop and store all the nodes.
s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
allNodes = []
for line in gfile.split():
nodes =line.split(":")[1].replace(';',',').split(',')
for node in nodes:
allNodes.append(node)
return allNodes
print read_nodes(s)
Not quite sure what you are ultimately trying to accomplish but this will print what you say you are expecting:
s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
nodes = []
for line in gfile.split():
nodes += line.split(":")[1].replace(';',',').split(',')
return nodes
print read_nodes(s)
Add the following code so that the output is
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N']
//Code to be added
nodes_list = []
def read_nodes(gfile):
for line in gfile.split():
nodes =line.split(":")[1].replace(';',',').split(',')
nodes_list.extend(nodes)
print nodes_list
print read_nodes(s)
graph={ 0:[1,3,4], 1:[0,2,4], 2:[1,6], 3:[0,4,6], 4:[0,1,3,5], 5:[4], 6:[2,3] }
def bfs(graph, start, path=[]):
queue = [start]
while queue:
vertex = queue.pop(0)
if vertex not in path:
path.append(vertex)
queue.extend(graph[vertex] - path)
return path
print bfs(graph, 0)
Guys! Can someone help me with this bfs code? I can't understand how to solve this queue line.
To extend your queue with all nodes not yet seen on the path, use set operations:
queue.extend(set(graph[vertex]).difference(path))
or use a generator expression:
queue.extend(node for node in graph[vertex] if node not in path)
Lists don't support subtraction.
You don't really need to filter the nodes, however, your code would work with a simple:
queue.extend(graph[vertex])
as the if vertex not in path: test also guards against re-visiting nodes.
You should not use a list as default argument, see "Least Astonishment" and the Mutable Default Argument; you don't need a default argument here at all:
def bfs(graph, start):
path = []
Demo:
>>> graph={ 0:[1,3,4], 1:[0,2,4], 2:[1,6], 3:[0,4,6], 4:[0,1,3,5], 5:[4], 6:[2,3] }
>>> def bfs(graph, start):
... path = []
... queue = [start]
... while queue:
... vertex = queue.pop(0)
... if vertex not in path:
... path.append(vertex)
... queue.extend(graph[vertex])
... return path
...
>>> print bfs(graph, 0)
[0, 1, 3, 4, 2, 6, 5]
queue.extend(graph[vertex] - path)
This line is giving TypeError: unsupported operand type(s) for -: 'list' and 'list', because you are not allowed to subtract two lists. You could convert them to a different collection that does support differences. For example:
graph={ 0:[1,3,4], 1:[0,2,4], 2:[1,6], 3:[0,4,6], 4:[0,1,3,5], 5:[4], 6:[2,3] }
def bfs(graph, start, path=[]):
queue = [start]
while queue:
vertex = queue.pop(0)
if vertex not in path:
path.append(vertex)
queue.extend(set(graph[vertex]) - set(path))
return path
print bfs(graph, 0)
Result:
[0, 1, 3, 4, 2, 6, 5]
By the way, it may be good to modify the argument list so that you don't have a mutable list as a default:
def bfs(graph, start, path=None):
if path == None: path = []
Bug is that there is no list difference method. Either you can convert it to set and use set difference method or you can use list comprehension as
queue.extend(graph[vertex] - path)
can be replaced by
queue += [i for i in graph[vertex] if i not in path].
#USE BELOW CODE FOR SIMPLE UNDERSTANDING
graph = {
'A' : ['B' , 'C','D'],
'B' : ['E'],
'C' : ['F'],
'D' : ['G'],
'E' : [],
'F' : ['Z'],
'G' : [],
'Z' : [],
}
visited = [] #Store visted nodes
queue = [] #BFS uses queue structure so this varible will work like QUEUE ( LIFO)
final_result = []
def bfs(visited,graph,node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print(s,end=" ")
#final_result.append(s)
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
bfs(visited,graph,'A')
print(final_result)
I am encoding a set of items using Huffman codes, and, along with the final codes, I'd like to return the intermediate nodes encoded as well, but with the the data of the child nodes concatenated into the the data of the intermediate node.
For example if I were to encode this set of symbols and probabilities:
tree = [('a',0.25),('b',0,25),('c',0.25),('d',0.125),('e',0.125)]
I'd like the following to be returned:
tree = [['ab','0'],['cde','1'],['a','00'],['b','01'],['c','10'],['de','11'],['d','110'],['e','111']]
I'm using the following code to produce Huffman trees:
import heapq
#symbfreq = list of symbols and associated frequencies
def encode(symbfreq):
#create a nested list as a tree
tree = [[wt, [sym, ""]] for sym, wt in symbfreq]
#turn the tree into a heap
heapq.heapify(tree)
while len(tree)>1:
#pop the lowest two nodes off the heap, sorted on the length
lo, hi = sorted([heapq.heappop(tree), heapq.heappop(tree)], key=len)
#add the next bit of the codeword
for pair in lo[1:]:
pair[1] = '0' + pair[1]
for pair in hi[1:]:
pair[1] = '1' + pair[1]
#push a new node, which is the sum of the two lowest probability nodes onto the heap
heapq.heappush(tree, [lo[0]+hi[0]] + lo[1:] + hi[1:])
return sorted(heapq.heappop(tree)[1:], key=lambda p: (len(p[-1]), p))
The Huffman algorithm is:
1.Create a leaf node for each symbol and add it to the priority queue.
2.While there is more than one node in the queue:
3.Remove the node of highest priority (lowest probability) twice to get two nodes.
4.Create a new internal node with these two nodes as children and with probability equal to the sum of the two nodes' probabilities.
5.Add the new node to the queue.
6.The remaining node is the root node and the tree is complete.
I can't for the life of me think of a way to stop the intermediate nodes being overwritten (i.e. I want to persist the intermediate nodes created at stage 4).
I don't know how do it while constructing (a part from building an output tree which is never popped), but you can retrieve the intermediary nodes quite easily :
huffman_tree = encode(tree)
complete_tree = huffman_tree
get_intermediate_node = lambda val, arr : ''.join( [ char for char,binary in itertools.ifilter( lambda node : node[1].startswith( val ),arr)] )
for val in range( next_power_of_two( len(huffman_tree) ) ):
bvalue = bin(val)[2:]
node = [ get_intermediate_node( bvalue , huffman_tree) , bvalue ]
if node not in complete_tree:
complete_tree.append( node)
print sorted( complete_tree , key=lambda p: (len(p[-1]), p) )
>>> [['ab', '0'], ['cde', '1'], ['a', '00'], ['b', '01'], ['c', '10'],
['de', '11'], ['', '100'], ['', '101'], ['d', '110'], ['e', '111']]
(You still need to prune the empty nodes )