Start free

Intermediate · Sorting · 148 of 264

Closest pair

Find the smallest difference between any two numbers in a list. Tip: after sorting, the closest numbers are neighbours.

Input: at least two whole numbers on one line. Output: the smallest difference.

Examples

Input
10 3 7 1
Output
2
Input
5 5
Output
0
Input
100 1
Output
99

One more test checks other inputs when you press Check.

Stuck? The idea behind sorting

sorted() gives a new sorted list; list.sort() sorts the list itself. reverse=True sorts from largest to smallest.

key= says what to sort by: key=len sorts words by length, key=lambda p: p[1] sorts pairs by their second item.

people = [("Ann", 14), ("Bob", 12)]
for name, age in sorted(people, key=lambda p: p[1]):
    print(name, age)

Watch for: list.sort() gives back None: names = names.sort() loses the list. Use sorted() for a new one.

All the sorting exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More sorting exercises