Search code examples
python-3.xcombinationspython-itertools

Get different sets of numbers with repetition


I have a list of numbers:

lst = [1, 2, 3, 1,4]


def permutation(lst):
    # If lst is empty then there are no permutations
    if len(lst) == 0:
        return []

    # If there is only one element in lst then, only
    # one permuatation is possible
    if len(lst) == 1:
        return [lst]

        # Find the permutations for lst if there are
    # more than 1 characters

    l = []  # empty list that will store current permutation

    # Iterate the input(lst) and calculate the permutation
    for i in range(len(lst)):
        m = lst[i]

        # Extract lst[i] or m from the list.  remLst is
        # remaining list
        remLst = lst[:i] + lst[i + 1:]

        # Generating all permutations where m is first
        # element
        for p in permutation(remLst):
            l.append([m] + p)
    return l

if __name__ == "__main__":
    lst = [1, 2, 3, 1,4]
    v_out = permutation(lst)
    print(v_out)

I am only getting permutations of 4 length, I want permutatins of all lengths, and only distinct permutations. But within each permutation, repetition is allowed.


Solution

  • This should work... Using the permutations function from itertools and making a set out of everything to prevent duplicates from being added to the overall result

    In [20]: from itertools import permutations                                     
    
    In [21]: a = [1, 1, 2, 3]                                                       
    
    In [22]: all_results = set()                                                    
    
    In [23]: for i in range(1, len(a)): 
        ...:     all_results.update(set(permutations(a, i))) 
        ...:                                                                        
    
    In [24]: all_results                                                            
    Out[24]: 
    {(1,),
     (1, 1),
     (1, 1, 2),
     (1, 1, 3),
     (1, 2),
     (1, 2, 1),
     (1, 2, 3),
     (1, 3),
     (1, 3, 1),
     (1, 3, 2),
     (2,),
     (2, 1),
     (2, 1, 1),
     (2, 1, 3),
     (2, 3),
     (2, 3, 1),
     (3,),
     (3, 1),
     (3, 1, 1),
     (3, 1, 2),
     (3, 2),
     (3, 2, 1)}
    
    In [25]: