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
Post a Comment