We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
List comprehensions can do this easily, esp when you leverage that True == 1 and False == 0:
n, m = raw_input().split()
sc_ar = raw_input().split()
A = set(raw_input().split())
B = set(raw_input().split())
print sum([(i in A) - (i in B) for i in sc_ar])
It is because when u take input in form of string there is a possiblilty of adding whitespace at end, if that happens then split will also make a list of white space and further it would be bad for us to debug, therefore to avoid this we use rstrip() to remove any whitespaces at the end of stiring. Hope it helps. :)
so we can't solve using set operations???
like by using intersection operator in this Problem
because if we want to solve by set operator we need to convert main input into set
bro u have to use set for getting unique element ,list can't do that if u use list there is issue of duplicate element.
disjoint set means there is no common element in two sets. there is no meaning of disjoint without set cause disjoint is a property of set not list.
for e.g if your input is like:
A = 3, 4, 4, 2, 7, 2
if u make list of it then size is 6 but there is only 4 unique element but if u make set of it u get 4 different element in size of 4.
I hope u got the point if u have still any doublt then say.
i think its execution time limit.my code is also this lengthy and that;s why it showed me termination error in time.have to reduce the process of execution...
I think time limit might be the problem. This is a simple way to solve it:
n,m = input().split()
count = 0
array = input().split()
set_a,set_b = set(input().split()),set(input().split())
for i in array:
if i in set_a and i not in set_b: count += 1
if i in set_b and i not in set_a: count -= 1
print(count)
it will check for each element in sc_ar, if it's present in A count will be incremented. Similarly in B, then count(A) and count(B) will be subtracted.
Awesome solution, but you don't really need to sum list.
It is enough to sum generator expression which may be defined with no parentheses in this context:
print sum( (i in A) - (i in B) for i in sc_ar )
(don't mind whitespaces inside of sum() )
It leads to little economy of time because we don't waste it on creating list and storing it at some temporary place and only then summing elements of it.
Instead, we calculate each element on-the-fly, only when we need it
The time out error was because you weren't explicitly making A and B as sets.The inputs have duplicate values in A and B and we need to remove them. My code was also facing the same problem but now it's fixed.Have a look at this-
You have to provide some parameter to split() bif.It's default value is None so it won't work. The input is space-seperated so you have to call split(' ') on the input()! Just refer my code above!
Why the extra variable count??
You could just increment and decrement happiness directly.
WOW!
I had the def NoIdea: in my code and it didn't go through nor tell me that was the issue
Confidence restored but gosh those are hours I won't get back
I had a similar solutions and also it took too long.
So finally I changed from iterating over the entire list for every happy and every sad number to a counter dictionary like this:
your answer doesn't fullfill all the requirement of the question. Please read the input format again. If there is no usuage of n and m then why you inputted it.
I came up with the similar solution , but I got timeout error !
The second thing I want to ask is , why are we providing space " " between the split() . We have given I/Ps to other problems in this python challenge , does this space really matters??
Refer python documentation for split() function...
It's default value is None!
Also the inputs for firstSet and secSet are humungous lists!You need to convert them to sets. This will solve the timeout problem.
See my code,you'll get the idea.
( In this user will enter values,1st value will be assigned to n and 2nd value will be assigned to m)
arr = map(int, raw_input().split())
(In this all values user enters in a line(along with a space) will be entered into a group called arr..you can convert that arr into list or set afterwards)
I wrote the exact same code but instead of declaring A & B as sets, I declared them as lists. The code failed for 4 test cases because of timeout. Can someone explain the reason behind this?
The test cases are stress tests for your code.
which means they supply VERY long array of inputs.
when you use list instead of set, you are handling all the inputs instead of cutting them short with a set function and by thus reducing caculation time.
This it also why some of the for loops are failing and timeout. The time complexity of a loop to go through the array and check every integer if intersect with another array is a non effiecient coding.
I did face the same problem of time running out. Initially I did use A and B as lists rather than sets. Now that I use it as sets the problem seems to be resolved. Can you let me know the difference
I'm not quite sure why your solution got faster.
I means a set only containes unique items. But I think A and B did only have unique items anyway.
Do you want to show your code?
dont use list, the access time of list is little more than the set, due to which some testcases will not work properly.
try to use set only. And if you are coding in python 2 then use raw_input. this will improve the efficiency of the code.
In this case he had to read the values to get so that he could read in the later ones, since they are inputted in a specific order. It seems that the problem can be solved without n and m, but their inclusion makes finding a solution easier for beginners.
arr_set_size = input().split()
arr = input().split()
set1 = set(map(int, input().split()))
set2 = set(map(int, input().split()))
print(sum([(e in set1) - (e in set2) for e in arr]))
i wrote the same code but its still showing 0 instead of 1 for given input
3 2
1 5 3
3 1
5 7
Hi buddy,
[(e in set1) - (e in set2) for e in arr] produces [0,0,0] so you are getting result o.
use set1 = set(input().split()) instead of set(map(int, input().split())) this will solve your problem
Hi, we are using map only on set1 and set2 but not on array. I doubt this was causing the error.[(e in set1) - (e in set2) for e in arr] in this code we are getting false(0). You can use map on all three inputs(set1,set2 and array) which would give you desired result.
you are using map in sets that is elements of sets are integers but there is no map in arr that means the elements of array are still strings that's why your answer is 0(integers are being compared with strings)
use map in arr = map(int,input().split())
and everything will be fine
BTW Nice Beautiful Code Well Done
I don't think so, as we already know the sets are disjoint. It's more of a matter of finding out if a number belongs exclusively to one or the other set. It'll never be both.
See this python wiki on time complexity for information that you may find helpful. Sets, which use hashing, are needed to get a O(1) runtime on the 'in' operation. The other approach you used would linearly search through the entire collection before returning a false value for 'i in A'.
happy = 0
n, m = map(int, input().split())
array = list(set(map(int, input().split())))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
temp = a-b
for x in set(array):
if x in a:
happy+=1
if x in b:
happy-=1
print(happy)
This is my code. How come yours is taking less time and mine is taking more time and hence getting time out
Thanks for this comment. It worked !
My solution passed all test cases
n,m=input().split()
arr=list(map(int,input().split(' ')))
A=set(map(int,input().split(' ')))
B=set(map(int,input().split(' ')))
h=0
for i in arr:
if i in A:
h=h+1
if i in B:
h=h-1
print(h)
this was godmode turned on all the way, anyone can explain the set() over there? I had this implemented in a much longer code but it was working, only difference against this solution was the set.
I was getting timeout errors on the longer inputs.
why did you use set for A and B? Is not it already given that, there won't be any repeating element in A and B?
By the way, my code, which is same as above except the set part, got TLE. I am confused, if there is a problem with the test cases or, I am missing something?
This is my code it works fine for three test cases when input gets highers i am not able to store all the values in my arrset that's your "sc_ar" set for example in input i give 1000 values and i dont know y my length of arrset is only 916 ! please help me by telling where
i went wrong
Brother, Please tell how to compute Time complexity of your code,a rough idea: membership operator has worst case complexity O(n)
,so for each value in array, you intend to traverse both the sets (using in oprator).So, basically O(n*m),right,Please Rectify if i'm wrong
how this answer fullfills below reqiurement:
Input Format
The first line contains integers and separated by a space.
The second line contains integers, the elements of the array.
The third and fourth lines contain integers, and , respectively.
Isn't it more efficient to use a for loop? Because sets A and B are disjoint, if you find i in A then you don't need to check it in B. I don't really know list comprehesions, so maybe I'm missing something.
(i in A) and (i in B) checks for the number i in sets A and B and returns True and False for each check. "For i in sc_ar" goes through each number in sc_ar. Since True = 1 and False = 0 in python, (i in A) - (i in B) will be the net happiness derived from each number in sc_ar, since A adds happiness and B subtracts happiness. This solution thus adds them all in a list via [] (list comprehension) then proceeds to sum all the items in the list (which are all 1 or -1 for each number) to get the net solution.
Time Complexity of searching an element in a set is O(1) in average case and for searching in a list is O(n) in average case while in worst case, it is O(n) for both the data structures.
So we can say on an average, it will take less time when we use set in comparison to list.
I am attaching a link which will help you in comparing cost of various operations in Python.
https://wiki.python.org/moin/TimeComplexity
n,m=map(int,input().split())
arr=list(map(int,input().split()))
a=list(map(int,input().split()))
b=list(map(int,input().split()))
s=0
for i in arr:
if i in a:
s+=1
elif i in b:
s-=1
print(s)
simple solution to simple problem :- python 3 ->
n,m = input().split()
l = list(map(int,input().split()))
s1 = set(map(int,input().split()))
s2 = set(map(int,input().split()))
c = 0
for i in l:
if i in s1:
c+=1
if i in s2:
c-=1
print(c)
If you want to check items within it,using sets is more faster than lists.
But somehow if you want just iterate values , using lists is slightly faster than sets .
If I change A and B type into list like this:
A = list(raw_input().split())
B = list(raw_input().split())
Then it turned out Time out in some test cases ? Why ??
No Idea!
You are viewing a single comment's thread. Return to all comments →
List comprehensions can do this easily, esp when you leverage that True == 1 and False == 0:
here is problem solution in python programming. https://programs.programmingoneonone.com/2021/01/hackerrank-no-idea-solution-python.html
Here's my clean and elegant solution. Slightly different approach. Explanation added
HackerRank No Idea! Solution
Updated solution is here
https://www.thecscience.com/2021/08/HackerRank-No-Idea-in-python-problem-solution.html
I dont know why 5 test cases are wrong.kindly help
mystr=input()#Taking n.m no value for me so discard
mystr=input()
mystr=mystr.rstrip()
myset=set(mystr.split())
mystr=input()
mystr=mystr.rstrip()
mysetA=set(mystr.split())
mystr=input()
mystr=mystr.rstrip()
mysetB=set(mystr.split())
x = myset.intersection(mysetA)
xlen=len(x)
x = myset.intersection(mysetB)
ylen=len(x)
happiness=abs(xlen-ylen) print(happiness)
dont forget that the first array contains duplicate elements, when we put the array in set we negligate the duplicate elements.
Now Works perfectly....
mystr=input()
n,m=mystr.split()
mystr=input()
mystr=mystr.rstrip()
myset=mystr.split()
mystr=input()
mystr=mystr.rstrip()
mysetA=set(mystr.split())
mystr=input()
mystr=mystr.rstrip()
mysetB=set(mystr.split())
happiness=0
for i in myset:
print(happiness)
Why did you use rstrip?
It is because when u take input in form of string there is a possiblilty of adding whitespace at end, if that happens then split will also make a list of white space and further it would be bad for us to debug, therefore to avoid this we use rstrip() to remove any whitespaces at the end of stiring. Hope it helps. :)
so we can't solve using set operations??? like by using intersection operator in this Problem because if we want to solve by set operator we need to convert main input into set
bro can u please tell me what difference does set makes, why not simple array or list as we r already told that both sets are disjoint
bro u have to use set for getting unique element ,list can't do that if u use list there is issue of duplicate element. disjoint set means there is no common element in two sets. there is no meaning of disjoint without set cause disjoint is a property of set not list. for e.g if your input is like: A = 3, 4, 4, 2, 7, 2 if u make list of it then size is 6 but there is only 4 unique element but if u make set of it u get 4 different element in size of 4. I hope u got the point if u have still any doublt then say.
i think its execution time limit.my code is also this lengthy and that;s why it showed me termination error in time.have to reduce the process of execution...
I think time limit might be the problem. This is a simple way to solve it:
there is no use of keeping "and" in "if" statement, cuz setA and setB are already disjoint
You nailed it bro......Super
yeah I too face the same problem
print the intersection result if array have duplicate elements u can see result have only non repeated elements
this is insanely cool solution
kasam se
yes, not intuitive and intriguing how this person thought of it this way
hi could you please explain the sum([(i in A) - (i in B) for i in sc_ar]) part? does it match i (element in array against a and b and keep the count?)
No it will simply create a list of 0's and 1's then sum will be taken.
it will check for each element in sc_ar, if it's present in A count will be incremented. Similarly in B, then count(A) and count(B) will be subtracted.
If you want, at least in Pyhton 3, you can avoid the creation of the list inside of the sum((i in A) - (i in B) for i in sc_ar) .
can also do it in python 2 :D
Awesome solution, but you don't really need to sum list.
It is enough to sum generator expression which may be defined with no parentheses in this context:
print sum( (i in A) - (i in B) for i in sc_ar ) (don't mind whitespaces inside of sum() )
It leads to little economy of time because we don't waste it on creating list and storing it at some temporary place and only then summing elements of it.
Instead, we calculate each element on-the-fly, only when we need it
I agree with you about the "economy of time" becuase, my solution is below:
For some of the bigger test cases I was getting a time out error.
@ccjav; your solution is really efficient.
The time out error was because you weren't explicitly making A and B as sets.The inputs have duplicate values in A and B and we need to remove them. My code was also facing the same problem but now it's fixed.Have a look at this-
I agree that it's complexity is O(n) which is greater than O(m) and it takes one temperory variable.
this is basically the same solution I came up with but still getting an error(p.s I know I could be more efficient)
You have to provide some parameter to split() bif.It's default value is None so it won't work. The input is space-seperated so you have to call split(' ') on the input()! Just refer my code above!
Why the extra variable count?? You could just increment and decrement happiness directly.
Yeah I know, I couldnt figure out why it was not taking my code so I added the variable. I literally copied you code and still didn't go through
It's working for me though. What is the error you are getting?
WOW! I had the def NoIdea: in my code and it didn't go through nor tell me that was the issue Confidence restored but gosh those are hours I won't get back
you are not using n and m, so just do input()
I had a similar solutions and also it took too long. So finally I changed from iterating over the entire list for every happy and every sad number to a counter dictionary like this:
your answer doesn't fullfill all the requirement of the question. Please read the input format again. If there is no usuage of n and m then why you inputted it.
my solution is also same but time limit is exceeds
Check your solution again, you must be using list(set(map(int,a))) somewhere. Instead of that use set(map(int,a)).
Donot use count = 0 in else statement instead use count = count
correct
what is "ch" here ?
Dude, i can be present in both A and B. So, use 'if' instead of 'elif'.
I came up with the similar solution , but I got timeout error ! The second thing I want to ask is , why are we providing space " " between the split() . We have given I/Ps to other problems in this python challenge , does this space really matters??
PS : I am a beginner level 0 to be precise !
Refer python documentation for split() function... It's default value is None! Also the inputs for firstSet and secSet are humungous lists!You need to convert them to sets. This will solve the timeout problem. See my code,you'll get the idea.
It helps me , thank you!
make first and second set using A=set(map(int,input().split())) B=set(map(int,input().split()))
Use firstSet = set(map(int,firstSet)) after taking firstSet as input.
heyy can you explain what line 1,2,3,4 does
n,m = map(int, raw_input().split())
( In this user will enter values,1st value will be assigned to n and 2nd value will be assigned to m)
arr = map(int, raw_input().split()) (In this all values user enters in a line(along with a space) will be entered into a group called arr..you can convert that arr into list or set afterwards)
Well, I don't think there was any use of n,m.
Their question is hugely misleading, they explicitly claimed that A & B are sets, which made me think that the inputs are already unique...
Thanks for the tip though
They explicitly mentioned A and B are two disjoint sets and so it didn't occur to me that the data set will contain comon items between A and B.
I wrote the exact same code but instead of declaring A & B as sets, I declared them as lists. The code failed for 4 test cases because of timeout. Can someone explain the reason behind this?
The test cases are stress tests for your code. which means they supply VERY long array of inputs. when you use list instead of set, you are handling all the inputs instead of cutting them short with a set function and by thus reducing caculation time. This it also why some of the for loops are failing and timeout. The time complexity of a loop to go through the array and check every integer if intersect with another array is a non effiecient coding.
I did face the same problem of time running out. Initially I did use A and B as lists rather than sets. Now that I use it as sets the problem seems to be resolved. Can you let me know the difference
I'm not quite sure why your solution got faster. I means a set only containes unique items. But I think A and B did only have unique items anyway. Do you want to show your code?
I thought my input wasnt getting accepted as when i printed the setA it was empty
but can tell me that why are we using the first line as it seems no need of that
best code!! with clear understanding. thanxs man
The question they had asked is very confusing, Hacker rank sataements are ambigious , though your solution helped.
How would you notified bro.my code also exactly similar to you but in code instead of set I placed a list."Your analysis is great how do you do that?"
I used the same method but I am getting run time error.
Edit - I was using list(set(map(int,input().split()))) earlier. Just using set rectifies run time error problem
dont use list, the access time of list is little more than the set, due to which some testcases will not work properly. try to use set only. And if you are coding in python 2 then use raw_input. this will improve the efficiency of the code.
Could you elaborate a bit more on timeout issue, why is it happeing when calling list intstead of set on A and B? Here's my code that gave error
ar = list(map(int, input().rstrip().split())) A = list(map(int, input().rstrip().split())) B = list(map(int, input().rstrip().split()))
rest of the code is same as above.
Because set have a proporty to removes the same elements in a list
My algorithm is similar and timed out as well.
why do we have to right the first line ? becoz its not used later on this program..
In this case he had to read the values to get so that he could read in the later ones, since they are inputted in a specific order. It seems that the problem can be solved without n and m, but their inclusion makes finding a solution easier for beginners.
nice solution man
This comment changed because I missed something. Now that I see how it works, this is a very cool solution.
arr_set_size = input().split() arr = input().split() set1 = set(map(int, input().split())) set2 = set(map(int, input().split())) print(sum([(e in set1) - (e in set2) for e in arr])) i wrote the same code but its still showing 0 instead of 1 for given input 3 2 1 5 3 3 1 5 7
whats wrong with the code
why are you using .split() for for single input e.g array_set_size
there are 2 inputs in 1st line size of list and size of set (n and m)
Hi buddy, [(e in set1) - (e in set2) for e in arr] produces [0,0,0] so you are getting result o. use set1 = set(input().split()) instead of set(map(int, input().split())) this will solve your problem
Hi can you explain this, why this set(map(int, input().split())) gave a wrong answer
Hi, we are using map only on set1 and set2 but not on array. I doubt this was causing the error.[(e in set1) - (e in set2) for e in arr] in this code we are getting false(0). You can use map on all three inputs(set1,set2 and array) which would give you desired result.
@AnishKumarBojan, @sristi_gupta92
This line will create a list with strings
The following lines create sets with integers.
Their types are different. Thefore (e in set1) gives false every time. In order to fix it change
or
Both way would work same.
you are using map in sets that is elements of sets are integers but there is no map in arr that means the elements of array are still strings that's why your answer is 0(integers are being compared with strings) use map in arr = map(int,input().split()) and everything will be fine BTW Nice Beautiful Code Well Done
if i am changing the first line to map(int,input().split()), it is showing me the wrong answer. why is it so?
I did a for loop similar to this, but it timed out for some of the test case. Is there nay more optimal solution.
it is still showing terminated due to timeout
Would creating sets C = A - B and D = B - A save time by skipping cases where i is in A ( + 1) and in B ( - 1)?
I don't think so, as we already know the sets are disjoint. It's more of a matter of finding out if a number belongs exclusively to one or the other set. It'll never be both.
This is awesome!
absolute class man the point u have to play with list compression to get best out answer
You are awesome man. Really nice and easy solution.
Can anyone explain this line n, m = raw_input().split()?
Awesome solution.
Beautiful "True-False == 1".
See this python wiki on time complexity for information that you may find helpful. Sets, which use hashing, are needed to get a O(1) runtime on the 'in' operation. The other approach you used would linearly search through the entire collection before returning a false value for 'i in A'.
But the
for
and thesum
are two separate loops.I'm curious whether my solution is appreciably less efficient or just more verbose than @ccjav's. I also used Booleans as 1 and 0:
happy = 0 n, m = map(int, input().split()) array = list(set(map(int, input().split()))) a = list(map(int, input().split())) b = list(map(int, input().split())) temp = a-b for x in set(array): if x in a: happy+=1 if x in b: happy-=1 print(happy)
This is my code. How come yours is taking less time and mine is taking more time and hence getting time out
One thing I learn here is that, set is so much faster than list. Because set uses hash whereas list not. Thanks
Thanks for this comment. It worked ! My solution passed all test cases n,m=input().split() arr=list(map(int,input().split(' '))) A=set(map(int,input().split(' '))) B=set(map(int,input().split(' '))) h=0 for i in arr: if i in A: h=h+1 if i in B: h=h-1 print(h)
uber cool! I came up with something similar, i did not know that True equated to 1 in python
got wrong answer
How to input the arrays in python 2?
instead of input().split() write raw_input().split()
Thanks @ccjav for your code, but could you help me to fix what is wrong with this, few of the test cases are failing.
The integer array in the second line might contain duplicates.
You basically get rid of duplicates by converting it to a set, which leads to a wrong solution.
Test cases having large inputs are getting failes
Excellent example. Thank you for making it so conscise.
Just a quick note - the raw_input() is only in Python 2.x, this has been renamed to input() for Python3
This solution times out for me.
I just loved it. I did pretty much the same but it is way cooler.
this was godmode turned on all the way, anyone can explain the set() over there? I had this implemented in a much longer code but it was working, only difference against this solution was the set.
I was getting timeout errors on the longer inputs.
Can you help with my code? Last 5 Test cases are failing -
n, m = map(int, input().split())
arr = list(map(int, input().split()))
A = set(map(int, input().split()))
B = set(map(int, input().split()))
happiness = 0
happiness += len(A.intersection(arr))
happiness -= len(B.intersection(arr))
print(happiness)
Thanks in advance.
It's because duplicates exist in the 'arr' array which must be counted in happiness as well.
Thanks bro . I was doing similar thing
n_m = input().split() n_m = map(int, n_m) N = set(map(int, input().split())) A = set(map(int, input().split())) B = set(map(int, input().split()))
print(len(A.intersection(N))- len(B.intersection(N)))
Cool solution but doesn't really use sets. (The sets used in this case could easily be replaced by lists)
where you used n and m?
This solution rocks dude !!!
sum([(i in A) - (i in B) for i in sc_ar])
what does this function means..?
i in A return a boolean value, i.e. 1 for true and 0 for false. It is just adding 1 for all occurence of elements of sc_ar in A and -1 for B.
why did you use set for A and B? Is not it already given that, there won't be any repeating element in A and B? By the way, my code, which is same as above except the set part, got TLE. I am confused, if there is a problem with the test cases or, I am missing something?
Could you please explain the use of variable n, m here ? Seem like they are useless in your code
firstline=str(input()) happiness=0 arrset=set(input().split()) setA = set(input().split()) setB = set(input().split()) happiness += len(arrset.intersection(setA)) happiness -= len(arrset.intersection(setB)) print(happiness)
This is my code it works fine for three test cases when input gets highers i am not able to store all the values in my arrset that's your "sc_ar" set for example in input i give 1000 values and i dont know y my length of arrset is only 916 ! please help me by telling where i went wrong
arrset cant be a set because it contains duplicates, changing it into a set will remove the dupes causing the lesser amount of values in arrset
forget the limits..
Cool solution! what if we print instead: print(len(sc_ar.intersection(A))-len(sc_ar.intersection(B)))
The last 5 test cases were failed after running?Where is the use of getting n and m as inputs,in this code?
Brother, Please tell how to compute Time complexity of your code,a rough idea: membership operator has worst case complexity O(n) ,so for each value in array, you intend to traverse both the sets (using in oprator).So, basically O(n*m),right,Please Rectify if i'm wrong
This is not good solluation. Please tell us a right solluation if you know.
how this answer fullfills below reqiurement: Input Format
The first line contains integers and separated by a space. The second line contains integers, the elements of the array. The third and fourth lines contain integers, and , respectively.
I had no idea that True - False gives 1 as answer. Cool solution!
Not working for all test cases
YOU KILLED IT BRUHH..HATS OFFF
GOD
n, m = input().split()
(sc_ar, A, B) = [set (map(int,input().split())) for _ in range (3)]
print (sum([(i in A) - (i in B) for i in sc_ar]))
Isn't it more efficient to use a
for
loop? Because setsA
andB
are disjoint, if you findi
inA
then you don't need to check it inB
. I don't really know list comprehesions, so maybe I'm missing something.i use the same code but it gives timed out for some test cases how could your passed all test cases
can you show me your code
I would have never thought of this , really beautiful.
would you please explain how the last line work print sum([(i in A) - (i in B) for i in sc_ar]) or any alternative of this
(i in A) and (i in B) checks for the number i in sets A and B and returns True and False for each check. "For i in sc_ar" goes through each number in sc_ar. Since True = 1 and False = 0 in python, (i in A) - (i in B) will be the net happiness derived from each number in sc_ar, since A adds happiness and B subtracts happiness. This solution thus adds them all in a list via [] (list comprehension) then proceeds to sum all the items in the list (which are all 1 or -1 for each number) to get the net solution.
n, m = raw_input().split()
sc_ar = raw_input().split()
A = set(raw_input().split()) B = set(raw_input().split()) print sum([(i in A) - (i in B) for i in sc_ar])
can you explain why you use set in A and B i use without set not all test cases are passed
Time Complexity of searching an element in a set is O(1) in average case and for searching in a list is O(n) in average case while in worst case, it is O(n) for both the data structures. So we can say on an average, it will take less time when we use set in comparison to list. I am attaching a link which will help you in comparing cost of various operations in Python. https://wiki.python.org/moin/TimeComplexity
can you please explain this line print sum([(i in A) - (i in B) for i in sc_ar]) and can you give its python 3 verion . it would be so nice of you
but the n and the m here is useless
what this line mean ??
set(raw_input().split())
great
will it take O(n^2) or O(nlogn) ?
This is a cool solution but taking extra unnecessary memory.
wow boss my solution just showed excessive time use up
my code sucess in all the test cases Note-- >>> 2 line is not a set of elements (key point)
**i,j=input().split() Arr=[int(r) for r in input().split()] a=set([int(r2) for r2 in input().split()]) b=set([int(r3) for r3 in input().split()]) a1=0
for x in Arr: if x in a: a1+=1 elif x in b: a1-=1 print(a1) **
hii nice solution
I tried this solution but it is passing only 2 test cases. Rest all are failing.
Even my code below is also passing same 2 test cases only. Somebody can pls help?
n,m=input().split() arr=set(input().split()) a=set(input().split()) b=set(input().split())
add=len(arr.intersection(a)) sub=len(arr.intersection(b))
total=(add-sub)
print(total)
for research purpose only:
This seems to be inefficient with python 3.x
yes try this problem with latest version of the python
These two programs are not same??
n,m=map(int,input().split()) arr=list(map(int,input().split())) a=list(map(int,input().split())) b=list(map(int,input().split())) s=0 for i in arr: if i in a: s+=1 elif i in b: s-=1 print(s)
actually i got it i passed all test case because i was unaware that sets are faster than list.Sorry for the regret
It fails in some cases where test cases are very large. It exceeds time limit.
Hi, Could you please tell why following code is failing 4 test cases
n, m = map(int,input().split())
arr = map(int, input().split()) arr = list(map(int,arr))
a = set(map(int, input().split())) a = list(map(int,a)) b = set(map(int, input().split())) b = list(map(int,b))
add = 0 sub = 0
for i in arr: if i in a: add+=1 elif i in b: sub+=1
print(add-sub)
the problem is timeout not wrong answer because if you make a list , the complexity may become n*(m+m) (may be pass all indexes), a list have a positional access. but the data structure set there is no positional access , so the complixity become n https://stackoverflow.com/questions/1035008/what-is-the-difference-between-set-and-list
please explain me this code and problem statement also
How did you come up with this code?
simple solution to simple problem :- python 3 -> n,m = input().split() l = list(map(int,input().split())) s1 = set(map(int,input().split())) s2 = set(map(int,input().split())) c = 0 for i in l: if i in s1: c+=1 if i in s2: c-=1 print(c)
If you want to check items within it,using sets is more faster than lists. But somehow if you want just iterate values , using lists is slightly faster than sets .
Whoa! I never knew that this could be done
Brilliant solution!
Anyone plz explain me the meaning of the below line.
print sum([(i in A) - (i in B) for i in sc_ar])
Thanks in Advance:)
Updated one for python 3!!!
not argusted for repuitation of elemint in a and b
Thanks, I didn't know about raw_input and didn't really concieve the power of list comprehensions.
After 4 Years still its incredible, Mind Blowing !!
runtime error wrong sol
using list comprehension fails the time limit for me
If I change A and B type into list like this: A = list(raw_input().split()) B = list(raw_input().split()) Then it turned out Time out in some test cases ? Why ??
this code passed all test cases, this approach did'nt use list comprehension. solution in python 3
` len_int = list(map(int,input().split(" "))) n , m = len_int[0], len_int[1]
like_num = list(map(int,input().split(" "))) A = set(map(int,input().split(" "))) B = set(map(int,input().split(" "))) happiness = 0
for i in like_num: if i in A: happiness += 1 if i in B: happiness -= 1
print(happiness)
But isn't that an incorrect sytnax?
why do we make A and B sets? if i don't make them set 4 test cases fail. just because of the set thing?
I tried this, but some test cases are running out of time.
hey why ya wanna confuse python 2 with 3... those are absurdly diff....ahhhhh
i didn't get what m and n is required for
This doesn't pass on all test cases due to performance issue.