[英]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中, True
和False
分别等于1
和0
。 您可以利用此优势,并使用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.