Home > Mobile >  Bit stuck on finding the largest possible value under a limit
Bit stuck on finding the largest possible value under a limit

Time:06-01

I've been working on a Code Wars function

def prescribe(d, a, b):

Where the attempt is that given a target number d, say 4540, I want to calculate how close the number a, say 9, can get without exceeding the value. Alongside a bunch of other criteria. This is the working I have created so far:

sum = 0
x = int(d / a) * a
y = int(d / b) * b

if d % a == 0:
    return x
elif d % b == 0:
    return y
while d > sum:
    sum  = a   b
final = sum - (a   b)

if x > final and x > y:
    return x
elif y > final and y > sum:
    return y
else:
    return final

It's not the most efficient code admittedly, so bear with me. The main issue occurring here is that I can't quite seem to figure out how I can return the maximum possible value within the target d. So for instance when I call the function with the following parameters:

prescribe(4540, 9, 15)

The maximum value I return is with the number 9: 4536 when in actuality the answer is 4539. What I assume is the issue is the fact that I'm getting around the maximum possible value by simply dividing 4540 with 9, and then converting 504.4 into 504.0 with the int() function. When in reality I should be using 504.3.

I hope this illustrates the shortcoming I'm facing with my code—can't seem to figure out how I can get the maximum possible value within the target range. If anyone could advise me as to the limitation or way I should approach this I'd be very grateful.

CodePudding user response:

One string solution

def prescribe(d, a, b):
    return d - min((d - a * i) % b for i in range(d // a   1))


print(prescribe(4540, 9, 15))  # 4539

Explanation

So lets rephrase this task to

Find minimum r for a*x b*y r = d, where d, a, b are given parameters and x, y are variables

Solution for that is

  1. You have to iterate over every possible x (or y), but as far as a is positive you only have to iterate over [0, d//a] interval.
  2. Count r = (d - a * x) % b
  3. Find minimum between all the rs you recieved
  • Related