अगर मुझे पार्टी में देर हो रही हो तो क्षमा करें। ;)
यह जांचने के लिए कि क्या कोई set Aसबसेट है set B, Pythonहै A.issubset(B)और A <= B। यह setकेवल काम करता है और महान कार्य करता है लेकिन आंतरिक कार्यान्वयन की जटिलता अज्ञात है। संदर्भ: https://docs.python.org/2/library/sets.html#set-objects
मैं एक एल्गोरिथ्म के साथ जाँच करने के लिए आया था कि list Aक्या list Bनिम्नलिखित टिप्पणियों के साथ उपसमूह है ।
- सबसेट खोजने की जटिलता को कम करने के लिए, मैं
sortसबसे पहले दोनों सूचियों को उपयुक्त
मानता हूँ ताकि उपसमुच्चय के लिए अर्हता प्राप्त करने वाले तत्वों की तुलना की जा सके।
- इसने मेरी मदद
breakकी loopजब दूसरी सूची B[j]के तत्व का मूल्य पहली सूची के तत्व से अधिक है A[i]।
last_index_jशुरू करने के लिए प्रयोग किया जाता है loopसे अधिक list Bहै, जहां यह पिछले दूर छोड़ दिया। यह की शुरुआत से तुलना शुरू करने से बचने में मदद करता है
list B(जो यह है कि आप अनावश्यक लगता है कि हो सकता है के रूप में, शुरू करने के लिए list Bसे index 0बाद में iterations।)
जटिलता O(n ln n)दोनों सूचियों को छाँटने के O(n)लिए और सबसेट के लिए जाँच के लिए प्रत्येक होगी ।
O(n ln n) + O(n ln n) + O(n) = O(n ln n)।
कोड में यह printदेखने के लिए बहुत सारे कथन हैं कि प्रत्येक iterationमें क्या चल रहा है loop। ये केवल समझने के लिए हैं।
जांचें कि क्या एक सूची किसी अन्य सूची की सबसेट है
is_subset = True;
A = [9, 3, 11, 1, 7, 2];
B = [11, 4, 6, 2, 15, 1, 9, 8, 5, 3];
print(A, B);
# skip checking if list A has elements more than list B
if len(A) > len(B):
is_subset = False;
else:
# complexity of sorting using quicksort or merge sort: O(n ln n)
# use best sorting algorithm available to minimize complexity
A.sort();
B.sort();
print(A, B);
# complexity: O(n^2)
# for a in A:
# if a not in B:
# is_subset = False;
# break;
# complexity: O(n)
is_found = False;
last_index_j = 0;
for i in range(len(A)):
for j in range(last_index_j, len(B)):
is_found = False;
print("i=" + str(i) + ", j=" + str(j) + ", " + str(A[i]) + "==" + str(B[j]) + "?");
if B[j] <= A[i]:
if A[i] == B[j]:
is_found = True;
last_index_j = j;
else:
is_found = False;
break;
if is_found:
print("Found: " + str(A[i]));
last_index_j = last_index_j + 1;
break;
else:
print("Not found: " + str(A[i]));
if is_found == False:
is_subset = False;
break;
print("subset") if is_subset else print("not subset");
उत्पादन
[9, 3, 11, 1, 7, 2] [11, 4, 6, 2, 15, 1, 9, 8, 5, 3]
[1, 2, 3, 7, 9, 11] [1, 2, 3, 4, 5, 6, 8, 9, 11, 15]
i=0, j=0, 1==1?
Found: 1
i=1, j=1, 2==1?
Not found: 2
i=1, j=2, 2==2?
Found: 2
i=2, j=3, 3==3?
Found: 3
i=3, j=4, 7==4?
Not found: 7
i=3, j=5, 7==5?
Not found: 7
i=3, j=6, 7==6?
Not found: 7
i=3, j=7, 7==8?
not subset