Common elements in two lists preserving duplicates
Here is my suggestion:
from collections import Counter
ac=Counter(a)
bc=Counter(b)
res=[]
for i in set(a).intersection(set(b)):
res.extend([i] * min(bc[i], ac[i]))
>>> print(res)
[3, 5, 5]
Return the index of the common elements of two lists
try this:
lst1 = [1,0,0,1,1]
lst2 = [0,0,1,1,0]
[idx for idx, (f,s) in enumerate(zip(lst1,lst2)) if f==s]
#[1,3]
Edit: base on your comment. zip
concatenate element by element of two list. see this example:
a = [1,2,4,6,8]
b = [0,3,5,7,9]
list(zip(a,b))
# [(1, 0), (2, 3), (4, 5), (6, 7), (8, 9)]
find common elements in two lists in linear time complexity
To find them in linear time you should use some kind of hashing. The easiest way in Python is to use a dict:
list1 = [1, 8, 5, 3, 4]
list2 = [5, 4, 1, 3, 8]
common = set(list1).intersection(list2)
dict2 = {e: i for i, e in enumerate(list2) if e in common}
result = [(i, dict2[e]) for i, e in enumerate(list1) if e in common]
The result
will be
[(0, 2), (1, 4), (2, 0), (3, 3), (4, 1)]
You can use something like this to format and print it:
for i1, i2 in result:
print(f"list1[{i1}] with list2[{i2}]")
you get:
list1[0] with list2[2]
list1[1] with list2[4]
list1[2] with list2[0]
list1[3] with list2[3]
list1[4] with list2[1]
finding common elements between two lists?
considering inner array element can be non sorted way, sorting them according to the character order then comparing
A=[['TIF35', 'TIF35'], ['PTP1', 'SSM4'], ['AMD1', 'PRP40'], ['END3', 'RAD26']]
B=[['SDP1', 'SLT2'], ['ATG34', 'GCD7'], ['END3', 'RAD26'], ['TIF35', 'TIF35']]
tmp_b = [sorted(inner_list) for inner_list in B]
res = []
for inner_list in A:
if sorted(inner_list) in tmp_b:
res.append(inner_list)
print(res)
#OUTPUT [['TIF35', 'TIF35'], ['END3', 'RAD26']]
considering the inner list order of element not matter then using set operation as suggested by @patrickartner , this will make time complexit small
res = list(set(tuple(i) for i in A).intersection(set(tuple(i) for i in B)))
Common elements between two lists with no duplicates
- You are appending a list containing
i
toc
, soi not in c
will always returnTrue
. You should appendi
on its own:c.append(i)
Or
Simply use sets (if order is not important):
a = [1, 1, 2, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = set(a) & set(b) # & calculates the intersection.
print(c)
# {1, 2, 3, 5, 8, 13}
EDIT As @Ev. Kounis suggested in the comment, you will gain some speed by usingc = set(a).intersection(b)
.
Printing indices for common elements in two list
First off - you're overriding y
. So you're comparing x
to []
.
Also, you're updating y
as you go along, while comparing to it in your loop. That's error prone if I've ever seen it...
Next, why not use a simple list-comprehension?
indices_of_stuff_in_x_thats_also_in_y = [i for i, x_ in enumerate(x) if x_ in y]
print(indices_of_stuff_in_x_thats_also_in_y)
# [0, 1, 3, 4, 6]
One last comment - please note that your original definition kinda-sounds symmetric ("a list of indices for elements that are common in both x and y"). But it isn't and can't be, because you're talking about indices...
find common items in two lists using for loop python - reduce time complexity
You can combine a for-loop and an iterator to traverse the sorted lists in parallel and yield matches along the way.
def common(L1,L2):
iter2 = iter(sorted(L2)) # iterator on sorted L2 values
Done = object() # flag to identify end of iteration
v2 = next(iter2,Done) # get first (lowest) element of L2
for v1 in sorted(L1):
while v2 is not Done and v2<v1:
v2 = next(iter2,Done) # advance in sorted L2 to reach or surpass v1
if v1 == v2:
yield v1 # return matches
v2 = next(iter2,Done) # advance (only match items once each)
if v2 is Done: break # stop if L2 values exausted
for c in common([3,7,4,2,4,3,1],[4,5,2,2,4,3]):
print(c)
2
3
4
4
This will have a time complexity of O(NlogN + MlogM) instead of O(N*M) where N and M are the list sizes
Another solution you could have proposed is to use the Counter class which would have a complexity of O(N+M):
from collections import Counter
L1,L2 = [3,7,4,2,4,3,1],[4,5,2,2,4,3]
c = list((Counter(L1) & Counter(L2)).elements())
print(c) # [3, 4, 4, 2]
How to find the common elements of two lists?
Use sets
, its like a list, but can only hold unique items:
set(lista).intersection(listb)
Related Topics
How to Rotate an Image Gradually in Swing
Why Doesn't Java Offer Operator Overloading
What Is the "Continue" Keyword and How Does It Work in Java
Why Use a Prime Number in Hashcode
Best Way to List Files in Java, Sorted by Date Modified
What Causes "'Void' Type Not Allowed Here" Error
How to Kill a Thread? Without Using Stop();
Running Junit Tests in Parallel in a Maven Build
Producer/Consumer Threads Using a Queue
Module Error When Running Javafx Media Application
How to Implement Constants in Java
Why Can't Overriding Methods Throw Exceptions Broader Than the Overridden Method
Executorservice, How to Wait for All Tasks to Finish
Spring Boot and Multiple External Configuration Files
Jar Bundler Using Osxadapter Causing Application to Lag or Terminate
What Is the Correct Way to Structure This Kind of Data in Firestore