Categorize numbers of an array into different sets and count the occurences

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Categorize numbers of an array into different sets and count the occurences



I have a array of numbers. lets say A = [9,10,16,19]


A = [9,10,16,19]



I have four sets {8,9,10} , {11,12,13} ,{14,15,16}, {17,18,19,20}


{8,9,10} , {11,12,13} ,{14,15,16}, {17,18,19,20}



for each element in array A, categorize the element into the given sets and count the occurences correspond to each set.



considering the example i gave the output should be like [2,0,1,1]



what is the efficient way to do this??





What's the output like? How far have you tried solving it?
– Austin
12 mins ago







You mean you have for sets: {8,9,10} , {11,12,13} ,{14,15,16}, {17,18,19,20} ?
– scharette
8 mins ago




{8,9,10} , {11,12,13} ,{14,15,16}, {17,18,19,20}




2 Answers
2



I've used the set.intersection() method of set to do this:


set.intersection()


set


# Sets are generated with curly brackets
# or the set() constructor
mysets = [{8,9,10} , {11,12,13} , {14,15,16}, {17,18,19,20}]

# A is a list, which is a very different datatype
# For this problem here, it wouldn't make a difference if A
# were a set as well
A = [9,10,16,19]

[len(s.intersection(A)) for s in mysets]
>> [2, 0, 1, 1]





ya if they're actually sets and not lists, this is what you want
– kevinkayaks
47 secs ago


s0,s1,s2,s3 = [8,9,10] , [11,12,13] ,[14,15,16], [17,18,19,20]
sets = [s0,s1,s2,s3] #(these aren't sets, but ok)
A= [9,12,16,19]

numbers =
for s in sets:
n = sum(1 for x in s if x in A)
numbers.append(n)

# numbers[i] is the number of shared elements between A and sets[i]
# you should consider extension to duplicate elements.
# as written this may not give you the result you want on duplicate elements



The same thing as a one liner would read


numbers = [sum(1 for x in s if x in A) for s in sets]



Consider what you want to do with duplicate elements carefully. You may need to modify this






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

gg8iqSuwqy LA iX NBVsacx,EbEa52X0FbKzP3IJgBeHm
VmM5Q74V9PrKlusG2IO

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results