2017-09-01 22 views
0

我一直在生成隨機集和列表,並對如何計算給定集合或列表中的倍數數目感到好奇。我寫的代碼給了我錯誤的編號,所以我假設我已經錯誤地分配了一些東西。代碼是如何使用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) 

我是全新的編碼和此交換,所以任何幫助,將不勝感激。

+0

對不起,但我恐怕不理解_multiples_ _notion_至少在你的上下文中。可以分享一些示例 - 例如對於[48,3,31,13,35,49]'?它與_divisors_有什麼關係? – CristiFati

+0

你是說他計數獨特的價值?如果是這樣,你可以將你的值散列在[set](https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset)中並查找長度:'len(set( b))' – ti7

+0

對於這個例子,我正在查看集合中除了集合中的其他元素的元素,例如給定集合或列表(2,5,6,8)時,將會有兩個倍數,因爲2除以6和8. –

回答

0

這取決於您的意思是按列表中的倍數。

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 
+0

非常感謝您的評論!代碼運行良好。 –

0

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

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