Home > Software engineering >  How to create an Python function able to find the smallest multiple of 8 to handle batch jobs?
How to create an Python function able to find the smallest multiple of 8 to handle batch jobs?

Time:02-06

Lets say the function will receive an list of IDs like:

ids = [15, 16, 17]

In this scenario the desired OUTPUT should be:

24

Because the ranges will be:

1 to 24
25 to 48
...

On first range (1 to 24) will accommodate all the IDs (15, 16, 17)

Second example, lets say the function will receive an list of IDs like:

ids = [98, 99, 100, 101]

In this scenario the desired OUTPUT should be:

8

Because the ranges will be:

1 to 8
9 to 16
17 to 24
25 to 32
33 to 40
41 to 48
49 to 56
55 to 64
63 to 72
73 to 80
81 to 88
89 to 96
97 to 104

Last range (97 to 104) will accomodate the ids = [98, 99, 100, 101]

Testing this on OpenAI, the code generated is ALWAYS similar of:

def smallest_batch_size(ids):
    max_id = max(ids)
    batch_size = max_id
    while (batch_size % 8 != 0) or (max_id > batch_size):
        batch_size  = 1
    return batch_size

But cant give the desired OUTPUT for this problem, and after enter more details always occours the classic:

There was an error generating a response

CodePudding user response:

The question you're asking is basically "what is the smallest multiple of 8 where all ids (minus one) floor-divided by that have the same value" -- which you can code like this:

def smallest_batch_size(ids):
    i, j = min(ids), max(ids)
    return next(
        size for size in range(8, j   8, 8)
        if (i - 1) // size == (j - 1) // size
    )

assert smallest_batch_size([15, 16, 17]) == 24
assert smallest_batch_size([98, 99, 100, 101]) == 8
  • Related