-2

Custom Sort #

Description

Sort a list of integers basis the remainder they leave when divided by 5 in an ascending order, i.e. the number that leaves a lower remainder when divided by 5 should come before the number which leaves a higher remainder.

Hint: Use the appropriate ‘key’ in the sorted() function. If two integers leave the same remainder then their order — as in the original list — should be preserved.

Examples:

Input 1:

[1, 9, 35, 12, 13, 21, 10]

Output 1:

[35, 10, 1, 21, 12, 13, 9]

Community
  • 1
  • 1
user13526138
  • 41
  • 2
  • 7
  • 1
    Does this answer your question? [Custom Python list sorting](https://stackoverflow.com/questions/11850425/custom-python-list-sorting) – deadshot May 18 '20 at 18:19

2 Answers2

1
>>> sorted([1, 9, 35, 12, 13, 21, 10], key=lambda x: ("https://stackoverflow.com/questions/61876197", x % 5))
[35, 10, 1, 21, 12, 13, 9]
Samwise
  • 68,105
  • 3
  • 30
  • 44
-1

Just use a lambda expression for your sort function:

l = [1, 9, 35, 12, 13, 21, 10] 
sorted(l,key=lambda elem: elem%5)

Output:

[35, 10, 1, 21, 12, 13, 9]
Code Pope
  • 5,075
  • 8
  • 26
  • 68
  • @CodePope user13526138 doesn't have enough reputation to downvote – deadshot May 18 '20 at 18:24
  • @komatiraju032 Hmm, then I wonder who has downvoted this answer, while upvoting the other one, although mine is correct and have been sent first. – Code Pope May 18 '20 at 18:26