Untitled

mail@pastecode.io avatar
unknown
plain_text
14 days ago
1.3 kB
2
Indexable
Never
from collections import deque     
inp = [ ["A", "B"], ["B", "C"], ["C", "D"], ["D", None], ["X", None]]
inp = [ ["A", "B"], ["B", "C"], ["C", "D"], ["D", "F"], ["X", "Z"]]

def run(inp):
    preMap = {}
    visited = {}
    queue = deque()
    for dep in inp:
        visited[dep[0]]=False
        visited[dep[1]]=False
        # from collections import defaultdict
        # mp =  defaultdict(list)
        # Adding a default empty list for a dep, if its not there.
        if dep[1] not in preMap:
            preMap[dep[1]]=[]
        preMap[dep[1]].append(dep[0])
    print(preMap)
    print(visited)
    # If there is no None, we dont have a starting point to track, and tasks will never complete.
    if None not in preMap:
        return False
    queue.append(None)
    while len(queue) > 0:
        val = queue.popleft()
        if visited[val]:
            # cycle
            return False
        visited[val]=True
        if val not in preMap:
            # no dependencies for the key, so we skip this entry
            continue
        for deps in preMap[val]:
            queue.append(deps)
    print(visited)
    for key in visited.keys():
        if visited[key] == False:
            return False
    return True
print(run(inp))
print(run([ ["A", "B"], ["B", "C"], ["C", "D"], ["D", "A"], ["X", None]]))
    
Leave a Comment