Python | Remove all duplicates and permutations in nested list
Given a nested list, the task is to remove all duplicates and permutations in that nested list.
Input: [[-11, 0, 11], [-11, 11, 0], [-11, 0, 11], [-11, 2, -11], [-11, 2, -11], [-11, -11, 2]] Output: {(-11, 0, 11), (-11, -11, 2)} Input: [[-1, 5, 3], [3, 5, 0], [-1, 5, 3], [1, 3, 5], [-1, 3, 5], [5, -1, 3]] Output: {(1, 3, 5), (0, 3, 5), (-1, 3, 5)}
Code #1: Using Map
Python3
# Python code to remove all duplicates # and permutations in nested list #Initialisation listOfPermut = [[ - 11 , 0 , 11 ], [ - 11 , 11 , 0 ], [ - 11 , 0 , 11 ], [ - 11 , 2 , - 11 ], [ - 11 , - 11 , 2 ], [ 2 , - 11 , - 11 ]] # Sorting tuple then removing output = set ( map ( lambda x: tuple ( sorted (x)),listOfPermut)) # printing output print (output) |
Output:
{(-11, 0, 11), (-11, -11, 2)}
Code #2:
Python3
# Python code to remove all duplicates # and permutations in nested list # Initialisation input = [[ - 11 , 0 , 11 ], [ - 11 , 11 , 0 ], [ - 11 , 2 , - 11 ], [ - 11 , - 11 , 2 ], [ 2 , - 11 , - 11 ]] # Sorting tuple then removing output = set ( tuple ( sorted (x)) for x in input ) # printing output print (output) |
Output:
{(-11, 0, 11), (-11, -11, 2)}
Code #3: Using sort() and not in operator
Python3
# Python code to remove all duplicates # and permutations in nested list # Initialisation input = [[ - 11 , 0 , 11 ], [ - 11 , 11 , 0 ], [ - 11 , 2 , - 11 ], [ - 11 , - 11 , 2 ], [ 2 , - 11 , - 11 ]] # Sorting tuple then removing res = [] for i in input : i.sort() res.append(i) output = [] for i in res: if i not in output: output.append(i) output = list ( map ( tuple , output)) print ( tuple (output)) |
Output
((-11, 0, 11), (-11, -11, 2))
Code #4: Using operator.countOf() method
Python3
# Python code to remove all duplicates # and permutations in nested list import operator as op # Initialisation input = [[ - 11 , 0 , 11 ], [ - 11 , 11 , 0 ], [ - 11 , 2 , - 11 ], [ - 11 , - 11 , 2 ], [ 2 , - 11 , - 11 ]] # Sorting tuple then removing res = [] for i in input : i.sort() res.append(i) output = [] for i in res: if op.countOf(output, i) = = 0 : output.append(i) output = list ( map ( tuple , output)) print ( tuple (output)) |
Output
((-11, 0, 11), (-11, -11, 2))
Time Complexity: O(N*N)
Auxiliary Space: O(N*N)
Please Login to comment...