Python设置差异以从重复数组中查找丢失的元素
给定两个数组,除了一个元素外,它们彼此重复,即其中一个数组中的一个元素丢失,我们需要找到那个丢失的元素。
例子:
Input: A = [1, 4, 5, 7, 9]
B = [4, 5, 7, 9]
Output: [1]
1 is missing from second array.
Input: A = [2, 3, 4, 5
B = 2, 3, 4, 5, 6]
Output: [6]
6 is missing from first array.
我们有针对此问题的现有解决方案,请参阅从重复数组中查找丢失的元素。我们可以使用设置差异逻辑在Python中快速解决这个问题。方法很简单,只需在Set中转换两个列表,然后执行AB操作,其中len(A)>len(B)。
# Function to find lost element from a duplicate
# array
def lostElement(A,B):
# convert lists into set
A = set(A)
B = set(B)
# take difference of greater set with smaller
if len(A) > len(B):
print (list(A-B))
else:
print (list(B-A))
# Driver program
if __name__ == "__main__":
A = [1, 4, 5, 7, 9]
B = [4, 5, 7, 9]
lostElement(A,B)
输出:
[1]