You can download this code by clicking the button below.
This code is now available for download.
The function finds the smallest index difference of repeated elements in the list and returns it. If there are no repeated elements in the list, it returns None. The function first sorts the list, then uses binary search to determine the index of each prime number, and finally calculates the difference of the index list.
Technology Stack : bisect, collections.Counter, math.sqrt, sorted, bisect_left, bisect_right, Counter, find_diff, is_prime
Code Type : Function
Code Difficulty : Intermediate
def aordiff(a_list):
from bisect import bisect_left, bisect_right
from collections import Counter
from math import sqrt
def find_diff(lst):
count = Counter(lst)
for key, value in count.items():
if value > 1:
return key
return None
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
sorted_list = sorted(a_list)
prime_indices = []
for i in range(len(sorted_list)):
if is_prime(sorted_list[i]):
prime_indices.append(bisect_left(sorted_list, sorted_list[i]))
diff = find_diff(prime_indices)
return diff