Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I find the closest pair with the smallest difference in a single array?

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading