Python test if all N variables are different

Now I am making a program, and I was looking for it, but I cannot find a solution; My problem is where I want to make a condition where all the selected variables are not equal, and I can do it, but only with long lines of text, is there an easier way? My solution so far is to do:

if A!=B and A!=C and B!=C:

But I want to do this for several groups of five variables, and this is quite confusing for many. What can I do to make it easier?

+4
source share
4 answers

Create a set and check if the number of elements in the set matches the number of variables in the list that you passed to it:

>>> variables = [a, b, c, d, e]
>>> if len(set(variables)) == len(variables):
...     print("All variables are different")

, , , , , .

+18

- (, , __hash__), .

def check_all_unique(li):
    unique = set()
    for i in li:
        if i in unique: return False #hey I've seen you before...
        unique.add(i)
    return True #nope, saw no one twice.

O (n) . ( , , len(li) == len(set(li)), , )

( - ), :

def check_all_unique(li):
    li.sort()
    for i in range(1,len(li)):
       if li[i-1] == li[i]: return False
    return True 

O (nlogn), . , . , . ( - __cmp__ , , 1. wut 2. , .)

ne - , .

import operator
import itertools
li = #a list containing all the variables I must check
if all(operator.ne(*i) for i in itertools.combinations(li,2)):
   #do something

itertools.combinations, , operator.ne . O (n ^ 2), ( all ). , ne eq , operator.eq any.

: Vincent itertools,

import itertools
lst = #a list containing all the variables I must check
if all(a!=b for a,b in itertools.combinations(lst,2)):
   #do something

2: Uh, , , , heapq. O (nlogn) , O (n) . -

import heapq
def check_all_unique(li):
    heapq.heapify(li) #O(n), compared to sorting O(nlogn)
    prev = heapq.heappop(li)
    for _ in range(len(li)): #O(n)
       current = heapq.heappop(li) #O(logn)
       if current == prev: return False
       prev = current
    return True 
+5

Put the values ​​in the container type. Then just go through the container comparing each value. This would require O (n ^ 2).

pseudo code:

a[0] = A; a[1] = B ... a[n];

for i = 0 to n do
  for j = i + 1 to n do
      if a[i] == a[j]
         condition failed
0
source

You can list the list and verify that all values ​​are the first occurrence of this value in the list:

a = [5, 15, 20, 65, 48]
if all(a.index(v) == i for i, v in enumerate(a)):
    print "all elements are unique"

This allows a short circuit after detecting the first duplicate due to the behavior of the Python all () function.

Or, which is the same thing, list the list and check if there are any values ​​that are not the first occurrence of this value in the list:

a = [5, 15, 20, 65, 48]
if not any(a.index(v) != i for i, v in enumerate(a)):
    print "all elements are unique"
0
source

Source: https://habr.com/ru/post/1598616/


All Articles