有一个小需求:使用Python编写一个函数,两个列表arrayA和arrayB作为输入,将它们合并,删除重复元素,再对去重的列表进行排序,返回最终结果。 如果按照一步一步的做可以简单的写出如下Python代码:
# Challenge: write a function merge_arrays(), that takes two lists of integers as inputs.
# combines them, removes duplicates, sorts the combined list and returns it
def merge_arrays_vesion01(arrayA, arrayB):
arrayC = arrayA + arrayB
arrayD = list(set(arrayC))
arrayE = sorted(arrayD)
return arrayE我们可以对上述代码进行简化,直接先将arrayA+arrayB合并,然后使用set函数将合并后的arrayA+arrayB转换成集合,这样就取到去重的效果,最后对对集合调用sorted函数进行排序返回即可。对上述步骤直接简化,可以得到如下Python代码:
def merge_arrays(arrayA, arrayB):
return sorted(set(arrayA + arrayB))完整的测试代码如下:
# Challenge: write a function merge_arrays(), that takes two lists of integers as inputs.
# combines them, removes duplicates, sorts the combined list and returns it
def merge_arrays_vesion01(arrayA, arrayB):
arrayC = arrayA + arrayB
arrayD = list(set(arrayC))
arrayE = sorted(arrayD)
return arrayE
# 简化版本
def merge_arrays(arrayA, arrayB):
return sorted(set(arrayA + arrayB))
def test():
tests = {
1: [1, 2, 3, 4, 5] == merge_arrays([1, 2, 3, 4], [3, 4, 5]),
2: [3, 4, 5] == merge_arrays([3, 4, 5], [3, 4, 5]),
3: [1, 2, 3, 4, 5] == merge_arrays([1, 2], [3, 4, 5]),
4: [1, 2, 3, 4, 5] == merge_arrays([4, 3, 2, 1], [3, 4, 5]),
5: [2, 3, 4, 5] == merge_arrays([2, 2, 2, 2], [5, 4, 3])
}
if all(tests.values()):
print("Tests passed!")
else:
print("Tests failed")
if __name__ == '__main__':
test()上述代码写了5个测试用例,分别对merge_arrays函数进行验证,在Pycharm中的执行结果如下:
