簡體   English   中英

在 Python 中查找數字的倍數

[英]finding multiples of a number in Python

我正在嘗試編寫一個代碼,讓我找到一個數字的前幾個倍數。 這是我的嘗試之一:

def printMultiples(n, m):
for m in (n,m):
    print(n, end = ' ')

我發現,通過將for m in (n, m):中,無論數字是m ,它都會在循環中運行。

def printMultiples(n, m):
'takes n and m as integers and finds all first m multiples of n'
for m in (n,m):
    if n % 2 == 0:
        while n < 0:
            print(n)

經過多次搜索,我只能找到java中的示例代碼,因此我嘗試將其翻譯成python,但沒有得到任何結果。 我覺得我應該在這個地方使用range()函數,但我不知道在哪里。

如果你試圖找到m的第一個count倍數,這樣的事情會起作用:

def multiples(m, count):
    for i in range(count):
        print(i*m)

或者,您可以使用范圍執行此操作:

def multiples(m, count):
    for i in range(0,count*m,m):
        print(i)

請注意,這兩個都從0開始倍數 - 如果您想改為從m開始,則需要將其偏移這么多:

range(m,(count+1)*m,m)

這是做你想做的嗎?

print range(0, (m+1)*n, n)[1:]

對於 m=5,n=20

[20, 40, 60, 80, 100]

或者更好的是,

>>> print range(n, (m+1)*n, n)
[20, 40, 60, 80, 100] 

對於 Python3+

>>> print(list(range(n, (m+1)*n, n)))
[20, 40, 60, 80, 100] 

基於數學概念,我理解:

  • 所有除以n余數為0的自然數都是n的倍數

因此,以下計算也適用於解決方案(1 到 100 之間的倍數):

>>> multiples_5 = [n for n in range(1, 101) if n % 5 == 0]
>>> multiples_5
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]

進一步閱讀:

對於 5 的前十個倍數,比如說

>>> [5*n for n in range(1,10+1)]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

你可以做:

def mul_table(n,i=1):
    print(n*i)
    if i !=10:
        mul_table(n,i+1)
mul_table(7)

如果這是您正在尋找的 -

找出給定數字和極限之間的所有倍數

def find_multiples(integer, limit):
    return list(range(integer,limit+1, integer))

這應該返回 -

Test.assert_equals(find_multiples(5, 25), [5, 10, 15, 20, 25])

可以做的另一種方法是嘗試制作一個列表。 這是我獲取 7 的前 20 個倍數的示例。

輸入:

multiples_7 = [x * 7 for x in range(1,21)] 

print(multiples_7)

輸出:

[7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 105, 112, 119, 126, 133, 140]
def multiples(n,m,starting_from=1,increment_by=1):
    """
    # Where n is the number 10 and m is the number 2 from your example. 
    # In case you want to print the multiples starting from some other number other than 1 then you could use the starting_from parameter
    # In case you want to print every 2nd multiple or every 3rd multiple you could change the increment_by 
    """
    print [ n*x for x in range(starting_from,m+1,increment_by) ] 

對於 5 的前 10 個倍數,您可以這樣做

import numpy as np
#np.arange(1,11) array from 1 to 10 
array_multipleof5 = [5*n for n in np.arange(1,11)]
array_multipleof5 = np.array(array_multipleof5)
print(array_multipleof5)

如何在緊湊的 python 的 lambda 表示法中計算給定數字 x 的前 n 倍數

n_multiples_of_x = lambda n,x : list( range(x, x*n + 1, x) )

測試:

assert n_multiples_of_x(5, 5) == [5, 10, 15, 20, 25]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM