I've generated a list of combinations, using itertools
and I'm getting a result that looks like this:
nums = [-5,5,4,-3,0,0,4,-2]
x = [x for x in set(itertools.combinations(nums, 4)) if sum(x)==target]
>>> x = [(-5, 5, 0, 4), (-5, 5, 4, 0), (5, 4, -3, -2), (5, -3, 4, -2)]
What is the most time-complexity wise efficient way of removing unordered duplicates, such as x[0]
and x[1]
are the duplicates. Is there anything built in to handle this?
My general approach would be to create a counter of all elements in one and compare to the next. Would this be the best approach?
Thank you for any guidance.
You can use
itertools.combinations_with_replacement()
.Source: Python Docs
The best way is to not generate the duplicates in the first place.
The idea is to first create all possible combinations of values that appear multiple times, where each appears 0, 1, ... times. Then, we complete them with all possible combinations of the unique elements.
Output:
Since you want to find unordered duplicates the best way to go is by typecasting. Typecast them as
set
. Since set only contains immutable elements. So, I made a set oftuples
.