這取決於您的意思是按列表中的倍數。
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
對不起,但我恐怕不理解_multiples_ _notion_至少在你的上下文中。可以分享一些示例 - 例如對於[48,3,31,13,35,49]'?它與_divisors_有什麼關係? – CristiFati
你是說他計數獨特的價值?如果是這樣,你可以將你的值散列在[set](https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset)中並查找長度:'len(set( b))' – ti7
對於這個例子,我正在查看集合中除了集合中的其他元素的元素,例如給定集合或列表(2,5,6,8)時,將會有兩個倍數,因爲2除以6和8. –