Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if two dictionaries result in a loop

I have two dicts, where the dict inside the dict stands for the values in the other dict:

dict1 = {1:{1,3}, 2:{2}}
dict2 = {1:{5}, 3:{1}}

I am trying to find out, if the combination would result in a loop, for example:

dict1: 1 -> dict2: 3 -> dict1: 1; This would result in a loop, so my script should throw an error.

dict1: 2 -> not in dict2; Not a loop would be okay

dict1: 1 -> dict2: 1 -> 5 not in dict 1; Not a loop would be okay

Any ideas how I could solve that problem? Thanks in advance!

like image 381
Nicolas Avatar asked Nov 26 '25 21:11

Nicolas


1 Answers

If you just want to know if there is a loop between the two dictionaries you can use this code:

for key, values in dict1.items():
    if any([v in dict2 and key in dict2[v] for v in values]):
        print('loop found')

Otherwise, if you want to know where the specific loop is, you need to break out the iteration over values in the above code:

for key, values in dict1.items():
    for v in values:
        if v in dict2 and key in dict2[v]:
            print('loop found from ' + str(key) + ' through value ' + str(v) + ' back to ' + str(key))

For your sample data the output is either loop found for the first code snippet or loop found from 1 through value 3 back to 1 for the second.

like image 78
Nick Avatar answered Nov 28 '25 12:11

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!