Home > Net >  How to find the lowest difference between two numbers from the given list in python using loops?
How to find the lowest difference between two numbers from the given list in python using loops?

Time:07-10

I can't figure out how to make the random number in the list subtract each other than find the smallest difference. I can't use def() , sorted(), return or any import as they are not in the lesson yet.

def findMinDiff(arr, n):
    arr = sorted(arr)
    diff = 10**20
    for i in range(n-1):
        if arr[i 1] - arr[i] < diff:
            diff = arr[i 1] - arr[i]
    return diff
arr = [4, 1, 2, 9, 7, 100, 5, 0, 99, 100]
n = len(arr)
print("The lowest different between two numbers is "   str(findMinDiff(arr, n)))

Sample Output: The lowest different between two numbers is 0.

CodePudding user response:

To find the smallest difference between any two adjacent values in the list you could do this:

arr = [4, 1, 2, 9, 7, 100, 5, 0, 99, 100]

smallest_diff = float('inf')

for x, y in zip(arr, arr[1:]):
    if (diff := abs(x-y)) < smallest_diff:
        smallest_diff = diff
print(smallest_diff)

Output:

1

CodePudding user response:

Use a nested-loops as you mentioned in tags

min_diff = abs( arr[0] - arr[1] )
for i in range(len(arr)-1):
    for j in range(i 1,len(arr)):
        diff = abs( arr[i] - arr[j] )
        if diff < min_diff:
            min_diff = diff

Thanks to @stuart

  • Related