Skip to content

Commit 1354285

Browse files
committed
refactor(searches): Addressed failing build issue
Signed-off-by: Aditya Kumar <aditya.kumar60@infosys.com>
1 parent 141ed1c commit 1354285

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

searches/floyds_cycle_finding.py

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,26 +42,39 @@ 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 meet again.
5768
mu = 0
5869
tortoise = start_value
5970
while tortoise != hare:
6071
tortoise = successor_function(tortoise)
6172
hare = successor_function(hare)
6273
mu += 1
6374

64-
# Phase 3: find the length of the cycle (lam).
75+
# Phase 3: Find the length of the cycle (lam).
76+
# Fix the tortoise at the start of the cycle and move the hare
77+
# until it returns to the tortoise.
6578
lam = 1
6679
hare = successor_function(tortoise)
6780
while tortoise != hare:

0 commit comments

Comments
 (0)