Concept Introduction
In fact, the principle is similar, whether it is a three-way or a multi-way. The three-way set does not intersect, meaning that there are 3 sets of numbers, in any set, without the same element. and satisfies both: for any x, there is no x $ \in $ a,x $ \in $ B, and x $ \in $ C.
Achieve a
def disjoint1(A, B, C): """Return True if there is no element common to all three lists""" forin A: forin B: forin C: if==== c: returnFalse # we found a common vale returnTrue # if we reach this, sets are disjoint
Obviously, three-tier nesting, for a,b,c with a set length of n, the total time complexity is O ($ n^3 $).
Implementation two
def disjoint2 (A, B, C): "" "Return True If There is no element common to all three lists "" " for a in A: for b in B: if a = = B: # only check C if we found match from A and b for C in C: if a ==< /span> c: # (and thus a = = b = = C) return false # we found a common value return span class= "va" >true # if we reach this, sets is disjoint
To calculate the total time complexity, layers of analysis are required.
First, the outer loop A is O (n) and the inner loop b is O ($ n^2 $).
For if a== B, a total of O ($ n^2 $) Judgments will be executed.
The remaining time depends on the number of times (A, b) is equal. Because of the cross-specificity of the set, A and B are equal in number of N. Because once a = = B is established, then a is not equal to the element except B in B.
Because the number of a = = B is n, the time complexity of the most inner loop and its loop body is O ($ n^2 $).
Overall, the total time complexity is still O ($ n^2 $).
Summarize
With different algorithm time, the time complexity of program execution can be reduced, and the program is optimized to improve the efficiency.
Analysis of three-way set disjoint (Three-way set disjointness) algorithm