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
输出应该是最小的差值,对于这个问题应该是3。
我知道如何得到所有的差异,但我不知道如何过滤掉最小的差异。
您可以先对它进行排序,然后遍历它以寻找最小差异。
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)
输出:
3
在使用此技术查找最小差异时,可能需要处理两个问题:
- 在产生个体差异时保留最小值
- 取差值的绝对值(如果这是你想要的)
一些旁注:使用单个字母l
作为变量名确实令人困惑,因为它与数字1
相似。min
是一个内置函数,所以使用它作为变量名,虽然完全合法,但也可能令人困惑。
所以,在你的流结构中,使用内置的工具而不是库,你可以写:
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