Untitled
unknown
plain_text
2 years ago
1.4 kB
8
Indexable
ef longest_square_root_sequence(bag_list):
max_len = 0
sequence_lengths = {} # Dictionary to store the length of longest sequence ending at each number
for num in bag_list:
length = 1 # Length of sequence ending at the current number
# Check if sequence ending at this number has already been computed
if num in sequence_lengths:
continue
# Compute the square root of the current number
sqrt_num = num ** 0.5
# Loop while the square root is an integer and positive
while sqrt_num.is_integer() and sqrt_num > 0:
sqrt_num = int(sqrt_num) # Convert to integer if it's a perfect square
if sqrt_num in sequence_lengths:
# If sequence ending at the square root has already been computed,
# update the length and break out of the loop
length += sequence_lengths[sqrt_num] - 1
break
length += 1 # Increment the length of the sequence
sqrt_num = bag_list.index(sqrt_num) ** 0.5 # Update square root using index
# Update the maximum length
max_len = max(max_len, length)
# Store the length of the sequence ending at the current number
sequence_lengths[num] = length
return max_lenEditor is loading...
Leave a Comment