I have a code that creates a list of 20 random integers between 1 and 1000. And In the case of multiple existences of closest pair, I have to display the smallest pair.
This is what I have so far:
import random
numbers = [random.randint(1, 100) for num in range(20)]
print(numbers)
>Solution :
I would suggesting using numpy:
import random
import numpy as np
numbers = np.array([random.randint(1, 100) for num in range(20)])
numbers.sort()
# calc diff:
diff = numbers[1:] - numbers[:-1]
# get index minimal diff:
argmin = diff.argmin()
pair = numbers[argmin:argmin+2]
Output:
print(numbers) # already sorted
>>> [ 1 6 7 8 11 15 18 37 47 54 60 61 61 73 73 78 82 85 87 94]
print(diff)
>>> [ 5 1 1 3 4 3 19 10 7 6 1 0 12 0 5 4 3 2 7]
print(pair)
>>> array([61, 61])
This method will work in your case.