how to find 'cycle' for key-value pairs in a dictionary? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: how to find 'cycle' for key-value pairs in a dictionary? (/thread-21410.html) |
how to find 'cycle' for key-value pairs in a dictionary? - junnyfromthehood - Sep-29-2019 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. RE: how to find 'cycle' for key-value pairs in a dictionary? - ichabod801 - Sep-29-2019 This is a known problem in graph theory. Stack Overflow has a discussion of this. In Python this is implemented in the networkx package. |