-1

I want to find a list of unique items and sublists in a list in python 2.7

Input : [['P', 'Q'], [['not', 'P'], 'R'], [['not', 'R'], ['not', 'P']], [['not', 'Q'], 'S', ['not', 'T']], 'T']

Output: ['P','Q',['not','P'],'R',['not','R'],['not','Q'],'S',['not','T'],'T']

Can anyone suggest how to do it recursively?

My code :

def rem_dup(lis):
    y, s = [], set()
    for t in lis:
       w = tuple(sorted(t)) if isinstance(t, list) else t
       if not w in s:
          y.append(t)
          s.add(w)
    return y

def removeDuplicates(prop):
    if isinstance(prop, str):
        return prop
    else:
        out = [rem_dup(i) if isinstance(i, list) else i for i in rem_dup(prop)]
        return out 

I call removeDuplicates from main method and pass it input. I get below exception:

   if not w in s:
   TypeError: unhashable type: 'list'
skool99
  • 780
  • 1
  • 16
  • 35

1 Answers1

2

Recursive solution:

def unique(lst):
    s = set()
    for el in lst:
        if isinstance(el, str):
            s.add(el)
        elif el[0] == 'not'
            s.add(tuple(*el))
        else:
            s.update(unique(el))

    return s
Matt
  • 724
  • 4
  • 11