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
3 Answers 3
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])
1 Comment
itertools.def dupLists(List0,*Lists):
result=set(List0)
for l in Lists:
result=result.intersection(l)
if len(result)<2:
return True
return False
5 Comments
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.
5 Comments
has_key is totally obsolete and deprecated. Use the in keyword. instead. This has the advantage of being much faster in Python 2 and available in Python 3.has_key is a dirty habit carried forward from 2.3. I'll also point out that stackoverflow.com/questions/4374426/list-checking-in-python/… is the more robust, more correct solution.False for any duplicate.
([1,2,3],[1,4,5])to returnFalse? The first element in both after sorting is1, sox[0]==y[0], and it should return false. The question is, what do you mean by duplicating pairs?