问题
The last issue I have is being able to accurately compare two lists of the same size that have no elements in common. I cannot use any built in Python functions (i.e., sort, compare, Counter) except for list methods len, del, index.
My code:
def SameStuff(l1, l2):
if len(l1) <= 1 or len(l2) <= 1 or len(l1) != len(l2):
if len(l1) == 0 or len(l2) == 0:
return len(l1) == len(l2)
else:
return len(l1) == len(l2) and l1[0] == l2[0]
else:
if l1[0] == l2[0]:
return SameStuff(l1[1:], l2[1:])
else:
return SameStuff(l1, l2[1:]+[l2[0]])
回答1:
Your explanation is confusing:
compare two lists of the same size that have no elements in common
How do you compare lists that have nothing in common? It seems like you want to compare two lists to see if they contain the same elements, but in any order. As far as doing it only with the functions/methods len()
, del()
, and index()
, I believe it can be done with just index()
:
def SameStuff(l1, l2):
if l1 and l2: # both contain something
try:
index = l2.index(l1[0])
return SameStuff(l1[1:], l2[:index] + l2[1 + index:]) # recurse
except ValueError:
return False # a value in one wasn't found in the other
return not(l1 or l2) # only one contains something (False), or neither do (True)
This solution is also not destructive to its arguments.
回答2:
The most efficient way to compare 2 lists with no regard to order is with collections.Counter
as it takes an average time complexity of just O(n), but since you can't use it, you can instead implement the same principal on your own using two dicts to keep track of the counts of each distinct item in each list:
def compare(l1, l2, d1=None, d2=None):
if not d1:
d1, d2 = {}, {}
if l1 and l2:
d1[l1.pop()] = d1.get(l1[-1], 0) + 1
d2[l2.pop()] = d2.get(l2[-1], 0) + 1
return compare(l1, l2, d1, d2)
elif not l1 and not l2:
return d1 == d2
return False
so that:
print(compare([2, 3, 5, 3], [3, 5, 2, 3]))
print(compare([2, 3, 5, 2], [3, 5, 2, 3]))
print(compare([2, 3, 5, 2], [3, 5, 2]))
would output:
True
False
False
Note that any approach that slices a list or uses list.index
is always going to be inefficient because it takes O(n) to do each of those for every item in the lists, resulting in O(n^2) overall time complexity.
回答3:
def SameStuff(l1, l2):
if l1 == []: return l2 == []
if len(l1) != len(l2): return False
else: return SameStuff(l1[1:], [x for x in l2 if x != l1[0]])
This works order independently.
And the following version allows also repetitions of elements in the lists.
def SameStuff(l1, l2):
if l1 == []: return l2 == []
elif len(l1) != len(l2): return False
elif l1[0] in l2:
i = l2.index(l1[0])
return SameStuff(l1[1:], l2[:i] + l2[i+1:])
else: return False
来源:https://stackoverflow.com/questions/52826662/how-to-recursively-compare-2-lists-in-python-unsorted-order-independent