[英]Python: Check if two arrays (may contain repeated elements) contain the same set of elements
I am trying to solve a homework problem. 我正在努力解决作业问题。
Q. Assume the existence of two arrays X and Y of m elements each. 问:假设每个m元素存在两个数组X和Y. Assume that they may possibly contain duplicates (ie, repeated elements), on which a total order relation is defined.
假设它们可能包含重复项(即重复元素),在其上定义了总顺序关系。 a) Develop an efficient algorithm for determining if X and Y contains the same set of elements.
a)开发一种有效的算法,用于确定X和Y是否包含相同的元素集。
Now, to make this as efficient as possible, someone suggested using Hash tables. 现在,为了使其尽可能高效,有人建议使用哈希表。 I have been trying to implement it.
我一直在努力实现它。
I have already created the arrays and the hashtable, then I imported one array into the hashtable. 我已经创建了数组和哈希表,然后我将一个数组导入哈希表。
At this point I am looking for the most efficient way to search the array and give me the answer. 在这一点上,我正在寻找最有效的搜索阵列的方法,并给我答案。
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
If someone could kindly guide me further as to the logic I need here, that would be much appreciated. 如果有人能够进一步指导我在这里需要的逻辑,那将非常感激。
This is my solution. 这是我的解决方案。 Is this the most efficient solution?
这是最有效的解决方案吗? What would be the time complexity?
什么是时间复杂性? I am guessing O(n).
我在猜O(n)。 Am I correct?
我对么?
# 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.