Inbar Rose
Inbar Rose

Reputation: 43457

variable +=% possible or how to get the next interval of a number after another number

I want to be able to do something like the following...

Say I want a list of every number from 100-500 that is a multiple of 33.

>>> a = 100
>>> b = 500
>>> range(a,b,33)
[100, 133, 166, 199, 232, 265, 298, 331, 364, 397, 430, 463, 496]

This is not what I want, this is because a is not a multiple of 33.

To get the next multiple of 33 from a I can do:

a = a - a % 33 + 33

I want to know if there is an easier way to do this so that if I want to create this range without knowing the actual values and without having to define them beforehand..

Such as:

>>> def multiple(a, b, c):
    return range(a+=%c, b, c) #if this was possible

And obviously it would return me a range which would be correct, for example:

>>> multiple(100, 500, 33)
[132, 165, 198, 231, 264, 297, 330, 363, 396, 429, 462, 495]

I am aware I can do something simple like:

range(a - a%c + c, b, c)

However, without getting into details, calling the value of a is expensive for me in my case, and I would like to be able to find a way to not have to call it a second time, and also the above method is really not nice looking at all.

I really was not sure what the title of my question should be, but I suppose what I am looking for is a way to find the next multiple of a number after another given number.

Thank you.

Upvotes: 1

Views: 248

Answers (2)

NPE
NPE

Reputation: 500475

The following does what you want and only uses a once:

In [4]: range((a + c - 1) // c * c, b + 1, c)
Out[4]: [132, 165, 198, 231, 264, 297, 330, 363, 396, 429, 462, 495]

I would still place it into a helper function, rendering moot the question of how many times a is used.

Unlike the code in your question, this actually works correctly for cases when a is evenly divisible by c. Also, unlike the code in your question, it includes b in the range (as it should, according to your answer to my question in the comments):

In [15]: range((a + c - 1) // c * c, b + 1, c)
Out[15]: [66, 99, 132]

Upvotes: 3

Rohit Jain
Rohit Jain

Reputation: 213281

Well, to get the multiple of 33 everytime, you would need to start with a multiple of 33 only.

So, start with first multiple of 33 after 100, because range function will just keep on adding 33 to get next multiples.

To get the first multiple of 33 after a number num, you can use: -

num / 33 * 33 + 33  <==>  (num / 33 + 1) * 33

So, for your range you can use: -

>>> a = 100
>>> b = 500
>>> a = (a / 33 + 1) * 33
>>> range(a, b, 33)
[132, 165, 198, 231, 264, 297, 330, 363, 396, 429, 462, 495]

Upvotes: 0

Related Questions