Created
December 10, 2014 21:36
-
-
Save nboubakr/34370fa355fc9cddf307 to your computer and use it in GitHub Desktop.
Union of two sorted sequences (A and B aren't empty)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def union(A, i, B, j, C): | |
if (i >= len(A)) and (j >= len(B)) and (max(A[-1], B[-1]) == C[-1]): | |
return C | |
if (i == len(A)) and (j <= len(B)) and (C[-1] < B[j]): | |
C.append(B[j]) | |
return union(A, i, B, j + 1, C) | |
if (j == len(B)) and (i <= len(A)) and (C[-1] < A[i]): | |
C.append(A[i]) | |
return union(A, i + 1, B, j, C) | |
if A[i] < B[j]: | |
C.append(A[i]) | |
return union(A, i + 1, B, j, C) | |
elif A[i] == B[j]: | |
C.append(A[i]) | |
return union(A, i + 1, B, j + 1, C) | |
else: | |
C.append(B[j]) | |
return union(A, i, B, j + 1, C) | |
if __name__ == '__main__': | |
L1 = [2, 3, 5] | |
L2 = [1, 3, 5, 7] | |
print union(L2, 0, L1, 0, []) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment