Python Forum
how to find 'cycle' for key-value pairs in a dictionary?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to find 'cycle' for key-value pairs in a dictionary?
#1
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
Reply
#2
This is a known problem in graph theory. Stack Overflow has a discussion of this. In Python this is implemented in the networkx package.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  to find in dictionary given parameter 'name' and to output position Liki 10 1,395 Oct-08-2023, 06:38 AM
Last Post: Pedroski55
  Using dictionary to find the most sent emails from a file siliusu 6 7,611 Apr-22-2021, 06:07 PM
Last Post: siliusu
  2 Pairs 2 Lists Harshil 7 2,913 Aug-13-2020, 02:32 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020