0

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
Rod
  • 52,748
  • 3
  • 38
  • 55
HappyPy
  • 9,839
  • 13
  • 46
  • 68

2 Answers2

2

Using the lcm() function from this answer:

def my_fun(a, b):
    n = lcm(a, b)
    arange = range(0, n+1, n // a if n > a else a)
    brange = range(0, n+1, n // b if n > b else b)
    m = min(x - y for x in arange for y in brange if x > y)
    return [m, n//b + 1]

This is assuming your values a and b are integers, if you need to do this for floats just multiply by some power of 10 to make them ints. So for example with a=2.34 and b=3.73 you would multiply by 100, run my_fun(234, 373), and then divide the first value of the result by 100 (the second value can be used as is).

Here is the lcm() function and gcd() function that it depends on:

def gcd(a, b):
    """Return greatest common divisor using Euclid's Algorithm."""
    while b:      
        a, b = b, a % b
    return a

def lcm(a, b):
    """Return lowest common multiple."""
    return a * b // gcd(a, b)
Community
  • 1
  • 1
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
2
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)
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197