簡體   English   中英

如何使用Python計算集合或列表中的倍數數量?

[英]How does one calculate the number of multiples in a set or list using Python?

我一直在生成隨機集合和列表,並對如何計算給定集合或列表中倍數的數量感到好奇。 我寫的代碼給了我錯誤的號碼,所以我假設我分配的東西不正確。 該代碼是

b= random.sample(range(1, 56), 6)
print(b)
numbers = (b)
count_multiples = 0
for y in (b):
    for x in (b):
        if y % x ==0:
            count_multiples+=1
print("MPS:", count_multiples)

我是編碼和這種交流的新手,所以我們將不勝感激。

這取決於列表中倍數的確切含義。

1)。 由於每個數字都是自身的倍數,您是否要至少對每個數字計數一次?

2)。 如果一個元素是列表中一個以上元素的倍數,是否要計算一個以上元素?

如果您對這兩個問題的回答都是肯定的,則您的代碼看起來不錯(盡管不是最有效的)。 如果沒有,請嘗試以下操作:

min, max = 1, 56
n = 6
count = 0 
random_list_with_no_duplicates = random.sample(range(min, max), n)

# If no to 1) but yes to 2)
random_list_with_no_duplicates.sort()
for i in range(n):
    for j in range(i + 1, n):
        if random_list_with_no_duplicates[j] % random_list_with_no_duplicates[i] == 0:
            count += 1

# If no both
random_list_with_no_duplicates.sort(reverse=True)
for i in range(n):
    for j in range(i + 1, n):  # change to just 'i' if yes to 1), no to 2)
        if random_list_with_no_duplicates[i] % random_list_with_no_duplicates[j] == 0:
            count += 1
            break

在Python中, TrueFalse分別等於10 您可以利用此優勢,並使用sum將布爾值加在一起。 結果將是元素的數量e ,其中bool(e)值為True

count_multiples = sum(y % x == 0 for y in b for x in b)

暫無
暫無

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

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