@@ -42,26 +42,40 @@ def floyds_cycle_finding(
4242 >>> floyds_cycle_finding(get_next_node, 0)
4343
4444 """
45- # Main phase: finding a repetition x_i = x_2i.
45+ # Phase 1: Find a repetition x_i = x_2i.
46+ # The tortoise moves one step at a time, and the hare moves two.
47+ tortoise = start_value
48+ hare = successor_function (start_value )
49+
4650 # The hare moves twice as fast as the tortoise.
47- tortoise = successor_function ( start_value )
48- hare = successor_function ( successor_function ( start_value ))
51+ # The loop continues as long as they are not at the same value
52+ # and the hare has not reached the end of the sequence.
4953 while tortoise != hare :
50- # If the hare reaches the end of the sequence, there is no cycle.
51- if hare is None or successor_function (hare ) is None :
54+ if hare is None :
5255 return None
5356 tortoise = successor_function (tortoise )
54- hare = successor_function (successor_function (hare ))
5557
56- # Phase 2: find the position of the first repetition (mu).
58+ # Move hare two steps, with a check after each step.
59+ hare = successor_function (hare )
60+ if hare is None :
61+ return None
62+ hare = successor_function (hare )
63+
64+ # If the loop exits, a cycle was found.
65+
66+ # Phase 2: Find the position of the first repetition (mu).
67+ # Reset tortoise to the start and move both one step at a time until they
68+ # meet again.
5769 mu = 0
5870 tortoise = start_value
5971 while tortoise != hare :
6072 tortoise = successor_function (tortoise )
6173 hare = successor_function (hare )
6274 mu += 1
6375
64- # Phase 3: find the length of the cycle (lam).
76+ # Phase 3: Find the length of the cycle (lam).
77+ # Fix the tortoise at the start of the cycle and move the hare
78+ # until it returns to the tortoise.
6579 lam = 1
6680 hare = successor_function (tortoise )
6781 while tortoise != hare :
0 commit comments