which client has 10^5 numbers in his office? Do you do work for an entire telephone company?
Anyway:
print sum(1 for num in nums_dialed if num in client_nums)
That will give you as fast as possible the number.
If you want to do it for multiple clients, using the same nums_dialed list, then you could cache the data on each number first:
nums_dialed_dict = collections.defaultdict(int)
for num in nums_dialed:
nums_dialed_dict[num] += 1
Then just sum the ones on each client:
sum(nums_dialed_dict[num] for num in this_client_nums)
That would be a lot quicker than iterating over the entire list of numbers again for each client.
Answer from nosklo on Stack Overflowwhich client has 10^5 numbers in his office? Do you do work for an entire telephone company?
Anyway:
print sum(1 for num in nums_dialed if num in client_nums)
That will give you as fast as possible the number.
If you want to do it for multiple clients, using the same nums_dialed list, then you could cache the data on each number first:
nums_dialed_dict = collections.defaultdict(int)
for num in nums_dialed:
nums_dialed_dict[num] += 1
Then just sum the ones on each client:
sum(nums_dialed_dict[num] for num in this_client_nums)
That would be a lot quicker than iterating over the entire list of numbers again for each client.
>>> 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
>>>
Should be quite efficient even for the large numbers you quote.
Looks like you might be better off with a Counter:
>>> from collections import Counter
>>> mylist = ["Bob", "Mike", "Bob", "Mike", "Mike", "Mike", "Bob"]
>>> Counter(mylist)
Counter({'Mike': 4, 'Bob': 3})
use a dict of dicts to count, e.g. as follows:
tralala = dict()
for group, name in [('A', 'Bob'), ('B', 'Jane'), ('A', 'Bob')]:
tralala.setdefault(group, dict()).setdefault(name, 0)
tralala[group][name] += 1
print tralala
This results in
{'A': {'Bob': 2}, 'B': {'Jane': 1}}
If a set doesn't contain duplicates, then how does this work? I'm missing some key details of a set.
def count_duplicates(i):
unique_elements = set(i)
duplicates = []
for element in unique_elements:
if i.count(element) > 1:
duplicates.append((element, i.count(element)))
return i, unique_elements, duplicates
my_str = 'fuzz'
a,b,c = count_duplicates(my_str)
print(a)
print(b)
print(c)
[OUTPUT]
fuzz # initial string
{'f', 'u', 'z'} # set from string
[('z', 2)] # dict of duplicates with count