Python Forum

Full Version: how to find 'cycle' for key-value pairs in a dictionary?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In my homework, a cycle is defined as a set of keys that jump from key -> value -> key that returns to its original starting value. For instance:
d1 = {1:6, 3:1, 6:3}
cycles = [[1, 6, 3]]

because 1:6 -> 6:3 -> 3:1, and the starting key == last value

Similarly for the following dictionary:

d1 = {1: 5, 2: 14, 3: 15, 4: 3, 5: 5, 6: 5, 7: 15, 8: 6, 9: 10, 10: 15, 11: 12, 12: 15, 13: 14, 14: 8, 15: 9}
Properly ordered, the cycles given by the mapping are: [[5], [9, 10, 15]]
(also because 5:5 is a complete cycle, and 9:10 -> 10:15 -> 15:9)
Is there a way to create a loop to track these cycles in dictionaries? I wish to create a line that would work for any random key-value dictionary mappings.

Any help would be much appreciated. Heart
This is a known problem in graph theory. Stack Overflow has a discussion of this. In Python this is implemented in the networkx package.