【问题标题】:Python: Check if two arrays (may contain repeated elements) contain the same set of elementsPython:检查两个数组(可能包含重复的元素)是否包含相同的元素集
【发布时间】:2019-08-24 16:55:28
【问题描述】:

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

问。假设存在两个数组 X 和 Y,每个数组有 m 个元素。假设它们可能包含重复项(即重复的元素),在其上定义了总顺序关系。 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

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

【问题讨论】:

    标签: python list compare hashtable


    【解决方案1】:

    这是我的解决方案。这是最有效的解决方案吗?时间复杂度是多少?我猜是 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2021-12-14
      • 2016-10-13
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 2012-08-21
      相关资源
      最近更新 更多