Skip to content

Commit 1ce9e37

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

File tree

1 file changed

+24
-8
lines changed

1 file changed

+24
-8
lines changed

searches/floyds_cycle_finding.py

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,26 +42,42 @@ 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.
4646
# The hare moves twice as fast as the tortoise.
47+
# Start tortoise one step ahead and hare two steps ahead.
4748
tortoise = successor_function(start_value)
48-
hare = successor_function(successor_function(start_value))
49+
hare = successor_function(start_value)
50+
if hare is None:
51+
return None
52+
53+
hare = successor_function(hare)
54+
if hare is None:
55+
return None
56+
57+
# The main loop for finding a meeting point in the cycle.
4958
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:
52-
return None
59+
# Tortoise moves one step.
5360
tortoise = successor_function(tortoise)
54-
hare = successor_function(successor_function(hare))
5561

56-
# Phase 2: find the position of the first repetition (mu).
62+
# Hare moves two steps, with a check after each step to prevent errors.
63+
hare = successor_function(hare)
64+
if hare is None:
65+
return None
66+
hare = successor_function(hare)
67+
if hare is None:
68+
return None
69+
70+
# Phase 2: Find the position of the first repetition (mu).
71+
# Reset tortoise to the start and move both one step at a time until they meet.
5772
mu = 0
5873
tortoise = start_value
5974
while tortoise != hare:
6075
tortoise = successor_function(tortoise)
6176
hare = successor_function(hare)
6277
mu += 1
6378

64-
# Phase 3: find the length of the cycle (lam).
79+
# Phase 3: Find the length of the cycle (lam).
80+
# Fix the tortoise and move the hare until it returns to the tortoise.
6581
lam = 1
6682
hare = successor_function(tortoise)
6783
while tortoise != hare:

0 commit comments

Comments
 (0)