Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
any dups in this list?
#1
a function is working with several arguments and one of them is a list of some number of any type of object. one important requirement is that there be no duplicates in this list. if there are, the function will end up doing the wrong thing without detecting the error or raising an exception. so i am wanting to check it for dups before doing its thing. my first thought was to convert it to a set and see if len() stays the same or goes down. but elements of the list could be mutants (unhashable mutables). so it looks like i'm going to have to check the hard way, which could be O(n**2 * cmptime). so my next thought is to try the set thing under try/except. if it raises no exceptions, compare len(theset) and len(thelist) to see if the set has fewer. if an exception is raised, then fall back to the harder checking.

anything better around in Python?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
IF every element supports the equality operator (==), then you could use itertools.combinations to get the contents into two element pairs, and then use that with any() to check if any pairs are equal to each other. Something like:
>>> import itertools
>>> def unique(items):
...   pairs = itertools.combinations(items, 2)
...   is_equal = lambda pair: pair[0] == pair[1]
...   return not any(map(is_equal, pairs))
...
>>> unique([1, 2, "3", ["four"]])
True
>>> unique([1, 2, "3", ["four"], ("four", )])
True
>>> unique([1, 2, "3", ["four"], ("four", ), 2])
False
>>> unique([1, 2, "3", ["four"], ("four", ), ["four"]])
False
>>> unique([1, 2, "3", ["four"], ["four"]])
False
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020