Number of Elements in a Python Set

I have a list of phone numbers that have been dialed (nums_dialed). I also have a set of phone numbers, which are the number in the client’s office (client_nums). How to effectively determine how many times I called a particular client (total)

For instance:

>>>nums_dialed=[1,2,2,3,3]
>>>client_nums=set([2,3])
>>>???
total=4

The problem is that I have a big th data set: len (client_nums) ~ 10 ^ 5; and len (nums_dialed) ~ 10 ^ 3.

+3
source share
4 answers

which client has 10^5numbers in his office? Do you work for the entire telephone company?

Anyway:

print sum(1 for num in nums_dialed if num in client_nums)

This will give you the quantity as soon as possible.


, nums_dialed, :

nums_dialed_dict = collections.defaultdict(int)
for num in nums_dialed:
    nums_dialed_dict[num] += 1

:

sum(nums_dialed_dict[num] for num in this_client_nums)

, .

+8
>>> client_nums = set([2, 3])
>>> nums_dialed = [1, 2, 2, 3, 3]
>>> count = 0
>>> for num in nums_dialed:
...   if num in client_nums:
...     count += 1
... 
>>> count
4
>>> 

, .

+1

collection.Counter Python 2.7:

dialed_count = collections.Counter(nums_dialed)
count = sum(dialed_count[t] for t in client_nums)
+1

:

nums_dialed = [1, 2, 2, 3, 3]
client_nums = [2,3]

nums_dialed.sort()
client_nums.sort()

c = 0
i = iter(nums_dialed)
j = iter(client_nums)
try:
    a = i.next()
    b = j.next()
    while True:
        if a < b:
            a = i.next()
            continue
        if a > b:
            b = j.next()
            continue
        # a == b
        c += 1
        a = i.next() # next dialed
except StopIteration:
    pass

print c

"set" - ( , , ), . "" "", - , .

0

Source: https://habr.com/ru/post/1738752/


All Articles