简体   繁体   中英

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). Do you want to count every number at least once, since every number is a multiple of itself?

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. You can take advantage of this and use sum to add the booleans together. The result will be the number of elements, e , where bool(e) evaluates as True .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM