函数返回两个列表元素之间的最小差异 - python [英] function returning the smallest difference between elements of two lists - python

查看:237
本文介绍了函数返回两个列表元素之间的最小差异 - python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 a b 分别以2s和3s的恒定速率记录:

 >>> a 
0,2,4,6,8,10,12
>>> b
0,3,6,9,12

我想写一个函数在python中返回


  1. ab
  2. 实例的数量 b 以达到相同的值 a

所以在前面的例子中,


  1. ab 的最小差异为1,即当 a == 4 b == 3 (或 a == 10 b == 9

  2. 需要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)


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

  1. the smallest positive difference (i.e., bigger than zero) of a-b, and
  2. the number of instances that takes b to reach the same value of a.

So in the previous example,

  1. the smallest difference of a-b is 1, that is, when a==4 and b==3 (or a==10 and b==9)
  2. 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆