函数返回两个列表元素之间的最小差异

编程入门 行业动态 更新时间:2024-10-10 12:22:39
本文介绍了函数返回两个列表元素之间的最小差异 - python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

  • ab 实例的数量 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)

    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)

    更多推荐

    函数返回两个列表元素之间的最小差异

    本文发布于:2023-11-29 06:21:24,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1645591.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:函数   最小   差异   元素   两个

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!