简体   繁体   中英

Create a list of multiples of a number

Problem:

List of Multiples
Create a Python 3 function that takes two numbers (value, length) as arguments and returns a list of multiples of value until the size of the list reaches length.

Examples
list_of_multiples(value=7, length=5)[7, 14, 21, 28, 35]

list_of_multiples(value=12, length=10)[12, 24, 36, 48, 60, 72, 84, 96, 108, 120]

list_of_multiples(value=17, length=6)[17, 34, 51, 68, 85, 102]

def multiples (value,length):
    """
    Value is number to be multiply
    length is maximum number of iteration up to
    which multiple required.
    """
    for i in range(length):
        out=i
    return i

Most Pythonic Way

def multiples(value, length):
    return [*range(value, length*value+1, value)]

print(multiples(7, 5))
# [7, 14, 21, 28, 35]
print(multiples(12, 10))
# [12, 24, 36, 48, 60, 72, 84, 96, 108, 120]
print(multiples(17, 6))
# [17, 34, 51, 68, 85, 102]

Pythonic way:

def multiples(value, length):
    return [value * i for i in range(1, length + 1)]


print(multiples(7, 5))
# [7, 14, 21, 28, 35]
print(multiples(12, 10))
# [12, 24, 36, 48, 60, 72, 84, 96, 108, 120]
print(multiples(17, 6))
# [17, 34, 51, 68, 85, 102]
def multiples(value, length): list_multiples = [] i = 0 while i < length: list_multiples.append(value*(i+1)) i+=1 return list_multiples

The best answer for small values of length (< 100) is given by Nite Block .

However, in case length becomes bigger, using numpy is significantly faster than python loops:

numpy.arange(1, length+1) * value

With a length of 1000, python loops take almost 4 times longer than numpy. See code below:

import timeit

testcode_numpy = ''' 
import numpy
def multiples_numpy(value, length):
    return numpy.arange(1, length+1) * value
multiples_numpy(5, 1000)
'''

testcode = ''' 
def multiples(value, length):
    return [*range(value, length*value+1, value)]
multiples(5, 1000)
'''

print(timeit.timeit(testcode_numpy))
print(timeit.timeit(testcode))

# Result:
# without numpy: 9.7 s
# with numpy: 2.4 s

The easy / not in-line way would be :

def multiples(value, length):
    l = []
    for i in range(1, length+1):
        l.append(value*i)
    return l

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