函数返回两个列表元素之间的最小差异 - python [英] function returning the smallest difference between elements of two lists - python
本文介绍了函数返回两个列表元素之间的最小差异 - python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设 a
和 b
分别以2s和3s的恒定速率记录:
>>> a
0,2,4,6,8,10,12
>>> b
0,3,6,9,12
我想写一个函数在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 ofa
.
So in the previous example,
- the smallest difference of
a-b
is 1, that is, whena==4
andb==3
(ora==10
andb==9
) - it takes 3 instances of
b
to reach the same value ofa
(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文