Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning list into set and union operation

Tags:

python

list

union

def count1(x,s):
    def loop(x,s,count):
        while s!=[]:
            if x == s[0]:
                return loop(x,s[1:],count + 1)
            else:
                return loop(x,s[1:],count)
        if s==[]:
            return count
    return loop(x,s,0)

def remove_all1(x,s):
    def loop(x,s,ss):
        while s!=[]:
            if x == s[0]:
                return loop(x,s[2:],ss+[s[1]])
            else:
                return loop(x,s[1:],ss+[s[0]])
        return ss
    return loop(x,s,[])

def union0(xs,ys):
    ss = xs + ys
    for i in ss:
        #print(i)
        if count1(i,ss) > 1:
            return [ss[i]] + remove_all1(i,ss)
    return ss

print(union0([1,7,5,6],[9,9,0,6,4]))

This will print [0, 1, 7, 5, 9, 9, 0, 4], how to print [0,1,7,5,9,0,4]? To avoid the redundant, I know the set() way, but just want to know using the count0() and remove_all1() method.Thanks

like image 648
J.Doe Avatar asked Dec 30 '25 21:12

J.Doe


2 Answers

You can set.union after mapping all to sets:

def union(*lsts):
    return list(set.union(*map(set, lsts)))

Output:

In [2]: union([1, 7, 5, 6], [9, 9, 0, 6, 4], [1, 2])
Out[2]: [0, 1, 2, 4, 5, 6, 7, 9]

Or if you want the order they first appeared:

from collections import OrderedDict
from itertools import chain
def union(*lsts):
    return list(OrderedDict.fromkeys(chain(*lsts)))

Or to maintain order you could also create the set as you go:

from itertools import chain
def union(*lsts):
    st = set()
    for ele in chain(*lsts):
        if ele not in st:
            yield ele
        st.add(ele)

It makes absolutely no sense to use Counter dict to get a union of all the elements in the list, if you were trying to keep elements that appeared < n times then it would make sense.

like image 165
Padraic Cunningham Avatar answered Jan 02 '26 14:01

Padraic Cunningham


My solution.

import itertools
from collections import Counter

def union(*lists):
    joined = itertools.chain(*lists)  # joins all the arguments.
    counts = Counter(joined)  # counts elements in list.
    result = []
    for item, count in counts.items():
        if count >= 1:  # or any number you need
            result.append(item)  # or yield it.
    return result

print(union([1, 7, 5, 6], [9, 9, 0, 6, 4], [1, 2]))

Result:

[0, 1, 2, 4, 5, 6, 7, 9]

And some docs:

  • https://docs.python.org/2/library/collections.html#collections.Counter
  • https://docs.python.org/2/library/itertools.html#itertools.chain
like image 44
sobolevn Avatar answered Jan 02 '26 16:01

sobolevn