给出一个整数数组:
@IBAction func clear(_ sender: UIButton) {
canvas.clearCanvas()
}
程序应输出:
(-20, -5, 10, 15)
我首先尝试考虑伪代码:
对于数组中的每个元素 如果其绝对值大于nxt元素 交换它们
我将其实现为:
[-5, 10, 15, -20]
但是,当我们执行以下顺序时,它会失败:
def sort_by_abs(numbers_array: tuple) -> list:
numbers_array = list(numbers_array)
for i, number in enumerate(numbers_array):
if i == len(numbers_array) - 1:
break
elif abs(number) > abs(numbers_array[i+1]):
temp = number
numbers_array[i] = numbers_array[i+1]
numbers_array[i+1] = temp
return numbers_array
它输出
(1, 2, 3, 0)
我知道,当最初不需要移动的元素不存在时,可能会有其他数字向左移动
然后我尝试首先对列表进行排序,这样可以解决这种情况:
[1, 2, 0, 3]
但是,当我们有def sort_by_abs(numbers_array: tuple) -> list:
numbers_array = sorted(list(numbers_array))
for i, number in enumerate(numbers_array):
if i == len(numbers_array) - 1:
break
elif abs(number) > abs(numbers_array[i+1]):
temp = number
numbers_array[i] = numbers_array[i+1]
numbers_array[i+1] = temp
return numbers_array
时,它会输出(-1, -2, -3, 0)
,并且应该返回[-2, -1, 0, -3]
如何改进?
答案 0 :(得分:4)
只需使用内置abs
键的python内置sorted即可,该键的排序考虑了整数的绝对值
def sort_by_abs(numbers_array):
return sorted(tuple(numbers_array), key=abs)
print(sort_by_abs((-5, 10, 15, -20)))
print(sort_by_abs((-1, -2, -3, 0)))
print(sort_by_abs((1, 2, 3, 0)))
输出将为
[-5, 10, 15, -20]
[0, -1, -2, -3]
[0, 1, 2, 3]