Search code examples
pythonpython-3.xtuples

Difference between tuples that may have duplicates


I have two tuples, which may or may not have duplicated elements. I want to remove elements of tuple a that also occur in tuple b, taking into account multiplicity. That is,

a = (1, 2, 3), b = (2, 3, 4) => (1)
a = (1, 2, 2, 3), b = (2, 3, 4) => (1, 2)
a = (1, 2, 3), b = (2, 2, 3, 4) => (1)

I want to use these tuples as keys for @lrucache, so I need a hashable type.

I'm not even sure how to do this by hand if there is no better way.

Edit: This is a Python question, which I realized might not be obvious.


Solution

  • You can subtract elements with their frequencies using Counter.

    https://docs.python.org/3/library/collections.html#collections.Counter

    from collections import Counter as c
    a = (1, 2, 2, 3)
    b = (2, 3, 4)
    
    
    
    print(tuple((c(a)-c(b)).elements()))
    (1,2)
    

    Taking more complex example

    from collections import Counter as c
    a = (1, 2, 2, 2, 3, 5)
    b = (2, 3, 4)
    
    
    
    print(tuple((c(a)-c(b)).elements()))
    
    #outputs
    
    (1, 2, 2, 5)