简体   繁体   English

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

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

I have been generating random sets and lists and was curious about how one would calculate the number of multiples in that given set or list. 我一直在生成随机集合和列表,并对如何计算给定集合或列表中倍数的数量感到好奇。 The code I have written gives me the wrong number, so I am assuming I have allocated something incorrectly. 我写的代码给了我错误的号码,所以我假设我分配的东西不正确。 The code is 该代码是

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)

I am brand new to coding and this exchange, so any help would be appreciated. 我是编码和这种交流的新手,所以我们将不胜感激。

This depends on what exactly you mean by number of multiples in the list. 这取决于列表中倍数的确切含义。

1). 1)。 Do you want to count every number at least once, since every number is a multiple of itself? 由于每个数字都是自身的倍数,您是否要至少对每个数字计数一次?

2). 2)。 Do you want to count an element more than once if it is a multiple of more than one element in the list? 如果一个元素是列表中一个以上元素的倍数,是否要计算一个以上元素?

If you answer yes to both of these questions your code looks fine (although not the most efficient). 如果您对这两个问题的回答都是肯定的,则您的代码看起来不错(尽管不是最有效的)。 If no try something like the following: 如果没有,请尝试以下操作:

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

In Python, True and False are equal to 1 and 0 , respectively. 在Python中, TrueFalse分别等于10 You can take advantage of this and use sum to add the booleans together. 您可以利用此优势,并使用sum将布尔值加在一起。 The result will be the number of elements, e , where bool(e) evaluates as True . 结果将是元素的数量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