user457142
user457142

Reputation: 267

list checking in python

Hello there i've written a small functions that takes two lists and compares them for duplicating pairs, and returns a boolean value.

For instance ([1,2,3],[2,1,4]) returns false and ([1,2,3],[3,4,5]) returns true But i would like the argument to take any given amount of lists, instead of just two.

Here's my program so far:

def check(xrr, yrr):
    x = xrr[:]
    x.sort()
    y = yrr[:]
    y.sort()
    for i in range(len(x)-1):
        if x[i]==y[i]:
            return False
    return True

But also it isnt exactly working correctly yet, as ([1,2,3],[1,4,5]) also returns false.

Any hints and ideas is highly appreciated

Upvotes: 0

Views: 167

Answers (3)

MrGomez
MrGomez

Reputation: 23886

As a naive implementation, you can define a list of lists and hash the internal representation. For instance:

def check(given):
   hash = {}
   for li in given:
      for val in li:
         if val in hash:
            return False
         hash[val] = 1
   return True

This works if your input data sets contain a small number of unique elements relative to memory. If you expect to receive extremely large data sets, you might need to consider a more elaborate approach.

Also notable is this will return False for repeating elements within the same data set, and for repeating values at any location within the data set. This is trivial to refactor, or to rewrite entirely as the other solutions listed here.

Upvotes: 1

Kabie
Kabie

Reputation: 10663

def dupLists(List0,*Lists):
    result=set(List0)
    for l in Lists:
        result=result.intersection(l)
        if len(result)<2:
            return True
    return False

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

import itertools

def check(*args):
  r = None
  for l in args:
    s = set(frozenset(x) for x in itertools.combinations(l, 2))
    if r is None:
      r = s
    else:
      r &= s
    if not r:
      return True
  return False

print check([1, 2, 3], [3, 4, 5])
print check([1, 2, 3], [2, 1, 4])

Upvotes: 3

Related Questions