简体   繁体   中英

tuple unpacking in a list cannot be performed

Basically the question is to see if a number is a t-prime number or not (t-prime number has 3 distinct positive divisors), I have written the code it gives me a list like below:

[(4, 1), (4, 2), (4, 4), (5, 1), (5, 5), (6, 1), (6, 2), (6, 3), (6, 6)]

I need a func to return the number of j in each i value (i,j) in the list above, like 4 comes with three divisors, 5 comes with 2 etc..

https://codeforces.com/problemset/problem/230/B

'CODE'

# 230B

n = int(input())
a = list(map(int, input().split()))

lst = []
for j in range(len(a)):
    i = 1 
    while i <= a[j]:
        if a[j]%i == 0:
            lst.append((a[j],i))
        i += 1
print(lst)

please refer to previous page

It looks like your goal is to count the number of tuples with a given first element. Try this:

counter = {}
values = [(4, 1), (4, 2), (4, 4), (5, 1), (5, 5), (6, 1), (6, 2), (6, 3), (6, 6)]

for value, divisor in values:
    current = counter.get(value, 0) + 1
    counter[value] = current

Then, to get the count of a given value, use counter[n] . For instance, counter[4] would be 3 .

If your divisors are not guaranteed to be unique, then use sets for your dictionary values instead:

counter = {}
values = [(4, 1), (4, 2), (4, 4), (5, 1), (5, 5), (6, 1), (6, 2), (6, 3), (6, 6)]

for value, divisor in values:
    if value not in counter:
        counter[value] = set()
    counter[value].add(divisor)

Then, you can get the number of divisors with len(counter[n]) . So, len(counter[4]) would be 3 .

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