本文介绍了函数返回两个列表元素之间的最小差异 - python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设
- ab $ c的最小正差(即大于零) $ c $和
- 实例的数量 b 以达到相同的值 a 。
所以在前面的例子中,
- ab 的最小差异为1,即当 a == 4 和 b == 3 (或 a == 10 和 b == 9 )
- 需要3个 b 才能达到 a (即, 0,3,6 )。
理想情况下,我希望以这种方式使用该功能:
a = 2
b = 3
>>> my_fun(a,b)
>>> [1,3]#1 - 最小差异,3 - 实例数
解决方案 (a,b):
i,j,k = a,b,a
而a!= b:
如果< b:
a + = i
else:
n = a - b
k = n如果不是k else min(k,n)
b + = j
return k,b / j + 1
>>>工人(4,4)
(4,2)
>>>工人(2,3)
(1,3)
i,j,k = a,b,a
而a!= b:
如果< b:
a + = i
else:
n = a - b
k = n如果不是k else min(k,n)
b + = j
return k,b / j + 1
>>>工人(4,4)
(4,2)
>>>工人(2,3)
(1,3)
Let's say a and b are recorded at a constant rate of 2s and 3s respectively:
>>> a 0, 2, 4, 6, 8, 10, 12 >>> b 0, 3, 6, 9, 12
I'd like to write a function in python that returns
- the smallest positive difference (i.e., bigger than zero) of a-b, and
- the number of instances that takes b to reach the same value of a.
So in the previous example,
- the smallest difference of a-b is 1, that is, when a==4 and b==3 (or a==10 and b==9)
- it takes 3 instances of b to reach the same value of a (i.e., 0, 3, 6).
Ideally I'd like to use the function in this manner:
a = 2 b = 3 >>> my_fun(a,b) >>> [1, 3] #1-smallest difference, 3-number of instances
解决方案
def worker(a, b): i, j, k = a, b, a while a != b: if a < b: a += i else: n = a - b k = n if not k else min(k, n) b += j return k, b / j + 1 >>> worker(4, 4) (4, 2) >>> worker(2, 3) (1, 3)
这篇关于函数返回两个列表元素之间的最小差异 - python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
08-13 16:29