Home > OS >  Python all_unique with a custom comparator function
Python all_unique with a custom comparator function

Time:12-10

In this code snippet:

import more_itertools

def eq(a, b): return a%2 == b%3 # just a placeholder

a = [1, 7, 13]
print(more_itertools.all_unique(a))

I would like to use eq function to compare elements of a instead of equality. Is there a library function to accomplish that?

CodePudding user response:

If you don't mind implementing your own version of all_unique here is a relatively straightforward way to do it while enabling the use of a custom comparator function:

from operator import eq

def myeq(a, b):
    return a % 2 == b % 3

def all_unique(values, eqfunc=eq):
    for i, a in enumerate(values):
        for b in values[i 1:]:
            if eqfunc(a, b):
                return False
    return True

print(all_unique([1, 7, 13], myeq))

Output:

False

CodePudding user response:

You may be able to just hash it with a set and then see if the length is the same!

def all_unique(l):
    return len(set(l)) == len(l)
  • Related