Show common elements in a list and how many times they appeared in python -


i need make formula that, given 2 lists , b, returns common elements in , b. if same element appears more once in both, let's xa times in , xb times in b, x should appear min(xa,xb) times in results. if it's possible, don't use "import" in code, please.

for example: (supposing function called common(a,b))

common([1,3,3,3],[1,3,3,3,3,4]) => [1,3,3,3]

thank help!

a simple way sort 2 list first , compare first element 1 one. code this:

def common(a, b):     sorted_a, sorted_b = sorted(a), sorted(b)      numa, numb = len(a), len(b)     rv = []     i, j = 0, 0      while < numa , j < numb:         if sorted_a[i] == sorted_b[j]:             rv.append(sorted_a[i])             += 1             j += 1         elif sorted_a[i] < sorted_b[j]:             += 1         else:             j += 1     return rv 

Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -