码迷,mamicode.com
首页 > 其他好文 > 详细

Absolute sort

时间:2014-08-05 10:50:49      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   strong   for   ar   cti   div   

Absolute sort

Let‘s try some sorting. Here is an array with the specific rules.

The array (a tuple) has various numbers. You should sort it, but sort it by absolute value in ascending order. For example, the sequence (-20, -5, 10, 15) will be sorted like so: (-5, 10, 15, -20). Your function should return the sorted list or tuple.

Hints: This task can be easily solved using these functions: sorted andabs. You should try to use the key parameter for sorting.

Precondition: The numbers in the array are unique by their absolute values.

Input: An array of numbers , a tuple..

Output: The list or tuple (but not a generator) sorted by absolute values in ascending order.

 

题目大义:按绝对值排序

还是C语言的思路,sorted中传入cmp函数,如果x < y返回负值,x > y返回正值,x = y返回0

1 def cmp(numberA, numberB):
2     return abs(numberA) - abs(numberB)
3 
4 def checkio(numbers_array):
5     return sorted(numbers_array, cmp)

不过既然用了Python如此高大上的语言,自然要显摆下,sorted还有一个参数为key,实际上sorted(number_array, key=abs)即可

Absolute sort,布布扣,bubuko.com

Absolute sort

标签:blog   http   io   strong   for   ar   cti   div   

原文地址:http://www.cnblogs.com/hzhesi/p/3891492.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!