简体   繁体   中英

One-liner to calculate multiples of a certain number between two values in python

I have the following code to do what the title says:

def multiples(small, large, multiple):
     multiples = []
     for k in range(small, large+1):
             if k % multiple == 0:
                     multiples.append(k)
     return multiples

What it outputs:

>>> multiples(39, 51, 12)
[48]
>>> multiples(39, 51, 11)
[44]
>>> multiples(39, 51, 10)
[40, 50]
>>> multiples(39, 51, 9)
[45]
>>> multiples(39, 51, 8)
[40, 48]
>>> multiples(39, 51, 7)
[42, 49]
>>> multiples(39, 51, 6)
[42, 48]
>>> multiples(39, 51, 5)
[40, 45, 50]
>>> multiples(39, 51, 4)
[40, 44, 48]
>>> multiples(39, 51, 3)
[39, 42, 45, 48, 51]
>>> multiples(39, 51, 2)
[40, 42, 44, 46, 48, 50]

However, this is a lot of code to write, and I was looking for a pythonic one-liner to do what this does. Is there anything out there?

Just change your code to a List Comprehension, like this

return [k for k in range(small, large+1) if k % multiple == 0]

If you are just going to iterate through the results, then you can simply return a generator expression, like this

return (k for k in xrange(small, large+1) if k % multiple == 0)

If you really want to get all the multiples as a list, then you can convert that to a list like this

list(multiples(39, 51, 12))

You can do it as:

def get_multiples(low, high, num):
    return [i for i in range(low,high+1) if i%num==0]

Examples:

>>> print get_multiples(4, 345, 56)
[56, 112, 168, 224, 280, 336]

>>> print get_multiples(39, 51, 2)
[40, 42, 44, 46, 48, 50]

>>> print get_multiples(2, 1234, 43)
[43, 86, 129, 172, 215, 258, 301, 344, 387, 430, 473, 516, 559, 602, 645, 688, 731, 774, 817, 860, 903, 946, 989, 1032, 1075, 1118, 1161, 1204]
range((small+multiple-1)//multiple * multiple, large+1, multiple)

Perfect application for a generator expression:

>>> sm=31
>>> lg=51
>>> mult=5
>>> (m for m in xrange(sm,lg+1) if not m%mult)
<generator object <genexpr> at 0x101e3f2d0>
>>> list(_)
[35, 40, 45, 50]

If on Python3+, use range instead of xrange ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM