Home > database >  How to find the lowest difference between two numbers from the given list in python using nested whi
How to find the lowest difference between two numbers from the given list in python using nested whi

Time:07-18

    num = [100, 10, 200, 25, 7, 20]
    l = len(num)
    i = 0
    min = 0
    while i < l:
        j = i 1
        while j < l:
            ans = num[i] - num[j]
            print(f'{num[i]} diff {num[j]} is {ans}')
            j  = 1
        i  = 1

The output should be the lowest difference which should be 3 for this problem.

I know how to get all the difference but I don't know how to filter out the smallest difference.

CodePudding user response:

You may first sort it, and then loop through it for least difference.

num = [100, 10, 200, 25, 7, 20]
num.sort()
least_diff=None
for i in range(len(num)-1):
    diff=abs(num[i]-num[i 1])
    if not least_diff:
        least_diff=diff
    if diff<least_diff:
        least_diff=diff
print(least_diff)

Output:

3

CodePudding user response:

There's two issues that you probably need to deal with in finding the minimum difference using this technique:

  • retaining the minimum as you generate the individual differences
  • taking the absolute value of the difference (if that's what you want)

Couple of side notes: it is really confusing to use the single letter l as a variable name, given its resemblance to the digit 1. And min is a built-in function so using that as variable name, while totally legal, can also be confusing.

So, within your flow structure, and using just built-in facilities rather than libraries, you could write:

    num = [100, 10, 200, 25, 7, 20]
    sz = len(num)
    i = 0
    ans = abs(num[1]-num[0]) # initialize to a possible value
    while i < sz:
        j = i 1
        while j < sz:
            diff = abs(num[i] - num[j]) # take positive diff using abs built-in function
            # print(f'{num[i]} diff {num[j]} is {diff}')
            if diff < ans: # or could use min function or in-line-if
                ans = diff 
            j  = 1
        i  = 1
  • Related