Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping maximum and minimum values in a list

Tags:

python

Given a list (for instance, [1,1,2,1,2,2,3]) which is not sorted highest to lowest, and contains multiples of all numbers, I need to swap, in place, the maximums with the minimums, the second maxes with the second mins, etc. So, our example list would become [3,3,2,3,2,2,1].

Also, just to clarify, it's not just the max and min, but each layer of maxes and mins. So if the max was 4, 1's and 4's should switch as well as 2's and 3's.

I found this question on the topic: How to swap maximums with the minimums? (python)

but the code examples given seemed verbose, and assumed that there were no duplicates in the list. Is there really no better way to do this? It seems like a simple enough thing.

like image 551
Caleb Avatar asked Oct 06 '14 01:10

Caleb


1 Answers

This is one way to do it, possible because Python is such an expressive language:

>>> a = [1,1,2,1,2,2,3]
>>> d = dict(zip(sorted(set(a)), sorted(set(a), reverse=True)))
>>> [d[x] for x in a]
[3, 3, 2, 3, 2, 2, 1]
like image 68
Greg Hewgill Avatar answered Sep 28 '22 07:09

Greg Hewgill