class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
Select number of m elements from nums1 and n
element from nums2, then merge them into one
list in order.
"""
if m > len(nums1) or n > len(nums2):
return "Invalid input for m or n"
nums0 = list()
i = 0
j = 0
while i < m and j < n:
if nums1[i] <= nums2[j]:
nums0.append(nums1[i])
i += 1
else:
nums0.append(nums2[j])
j += 1
if i >= m:
nums0.extend(nums2[j:n])
elif j>=n:
nums0.extend(nums1[i:m])
return nums0, len(nums0)
def main():
s = Solution()
nums2 = [1,2,3,4,5]
nums1 = [4,5,6,7,8,9,10]
print s.merge(nums1, len(nums1), nums2, len(nums2))
print s.merge(nums1, 0, nums2, 1)
print s.merge(nums1, 5, nums2, 3)
if __name__ == "__main__":
main()
[[email protected] ~]# python merge_list2.py
([1, 2, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10], 12)
([1], 1)
([1, 2, 3, 4, 5, 6, 7, 8], 8)