Python:检查两个数组(可能包含重复的元素)是否包含相同的元素集

时间:2019-04-03 08:26:56

标签: python list compare hashtable

我正在尝试解决作业问题。

问:假设存在每个m个元素的两个数组X和Y。假设它们可能包含重复项(即重复元素),并在这些重复项上定义了总顺序关系。 a)开发一种有效的算法来确定X和Y是否包含相同的 元素集。

现在,为了尽可能提高效率,有人建议使用哈希表。我一直在尝试实现它。

我已经创建了数组和哈希表,然后将一个数组导入到哈希表中。

在这一点上,我正在寻找搜索阵列并给我答案的最有效方法。

dict = {'0':'-','1':'a','2':'b','3':'c'} #declare dictionary

print "first element of dict = ", dict['0']

print "\n"

array1 = ["4","5","6","7","8","9","10"]
print "array 1 = ", array1
array2 = ["4","5","6","7","8","9","10"]
print "array 2 = ", array2

print "\n"

print "array1[3] = ", array1[3]

print "\n"

print "clearing dictionary..."
dict.clear(); 

print "dict = ", dict

print "\n"

x = 0 #iterator for array1

print "importing array1 into dictionary..."

while x < len(array1) :
    dict[x] = array1[x]
    x += 1

print dict

y = 0 #iterator for array2

while y < len(array2) :
    if dict

如果有人可以进一步指导我这里需要的逻辑,将不胜感激。

1 个答案:

答案 0 :(得分:0)

这是我的解决方案。这是最有效的解决方案吗?时间的复杂度是多少?我猜是O(n)。我说得对吗?

# define first array
array1 = ["1","1","1","2"]
print "array 1 = ", array1

#define second array
array2 = ["1","2","3"]
print "array 2 = ", array2

#function
def is_empty(x, y):

    #find set difference between first and second array
    difference1 = set(x) - set(y)
    print difference1

    #find set difference between second and first array
    difference2 = set(y) - set(x)
    print difference2

    #union two differences together
    finalset = difference1.union(difference2)
    print finalset

    #if there are elements in finalset, arrays do not contain same set of elements
    if finalset:
        print('The sets do not contain the same set of elements.')
        return False

    #if there are no elements in final set, arrays contain same set of elements
    else:
        print('The sets contain the same set of elements.')
        return True

#function call on two arrays
is_empty(array1, array2)
相关问题