We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
classDirectedGraph:def__init__(self):self.graph={}defadd_node(self,node):"""Add a node to the graph."""ifnodenotinself.graph:self.graph[node]=[]defadd_edge(self,from_node,to_node):"""Add a directed edge from 'from_node' to 'to_node'."""iffrom_nodenotinself.graph:self.add_node(from_node)ifto_nodenotinself.graph:self.add_node(to_node)self.graph[from_node].append(to_node)defget_neighbors(self,node):"""Return a list of neighbors (outgoing edges) for a given node."""ifnodenotinself.graph:return[]returnself.graph[node]defget_no_incoming_nodes(self):"""Return a list of nodes with no incoming edges."""all_nodes=set(self.graph.keys())nodes_with_incoming=set()forneighborsinself.graph.values():forneighborinneighbors:nodes_with_incoming.add(neighbor)returnsorted(list(all_nodes-nodes_with_incoming))defremove_node(self,node):"""Remove a node and all edges connected to it (both incoming and outgoing)."""ifnodeinself.graph:delself.graph[node]forkeyinlist(self.graph.keys()):ifnodeinself.graph[key]:self.graph[key].remove(node)defremove_edge(self,from_node,to_node):"""Remove a directed edge from 'from_node' to 'to_node'."""iffrom_nodeinself.graphandto_nodeinself.graph[from_node]:self.graph[from_node].remove(to_node)defnum_nodes(self):"""Return the number of nodes in the graph."""returnlen(self.graph)defdisplay(self):"""Display the graph in an easy-to-read format."""fornode,neighborsinself.graph.items():print(f"{node} -> {neighbors}")# Example usageif__name__=="__main__":T=int(input())graph=[]foriinrange(T):chain=input()graph.append(chain)g=DirectedGraph()forchainingraph:g.add_node(chain[0])g.add_node(chain[1])g.add_edge(chain[0],chain[1])g.add_node(chain[2])g.add_edge(chain[1],chain[2])try:output=''whileg.num_nodes()>0:output+=g.get_no_incoming_nodes()[0]g.remove_node(g.get_no_incoming_nodes()[0])# print(g.get_no_incoming_nodes())# g.display()# print()print(output)except:print('SMTHWRONG')
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #79: Passcode derivation
You are viewing a single comment's thread. Return to all comments →
This is perfect python code : 100%