How to swap highs with lows? (Python)

Is there a way to change the maximum and minimum list?

The list will look like this, and the program should be continued so that it prints the maximum replacement with the minimum value, the second maximum is interchanged with the second minimum and the third maximum replaced by the third minimum.

Eg. Enter input-0 1 2 3 4 5 6 7 8 9 -1 Output-9873456210

a = []
nums = raw_input("Enter input- ")
for n in nums.split():
    n = int(n)
    if n < 0:
        break
    a.append(n)
if len(a)<7:
    print "please enter more than 7 integers"
-3
source share
3 answers

There is no method for this in python. You can try using primitive methods to create what you want to use in lists.

This code does the job:

#!/usr/bin/python
a = []
b = []
nums = raw_input("Enter input- ")
#append all to a list
for n in nums.split():
    n = int(n)
    if n < 0:
        break
    a.append(n)

#get the maximums
b = list(a)
first_max = max(b)
b.remove(first_max)
second_max = max(b)
b.remove(second_max)
third_max = max(b)

#get the minimums
b = list(a)
first_min = min(b)
b.remove(first_min)
second_min = min(b)
b.remove(second_min)
third_min = min(b)

## now swap 
xMax, yMax, zMax = a.index(first_max), a.index(second_max), a.index(third_max)
xMin, yMin, zMin = a.index(first_min), a.index(second_min), a.index(third_min)
a[xMax], a[xMin] = a[xMin], a[xMax]
a[yMax], a[yMin] = a[yMin], a[yMax]
a[zMax], a[zMin] = a[zMin], a[zMax]

print a
+1
source

, . , .

, .

data = list(range(10))
helper = sorted(data)
for i in range(3):
    low_value = helper[i]
    high_value = helper[-(i+1)]
    low_index = data.index(low_value)
    high_index = data.index(high_value)
    print(low_index, high_index)
    data[low_index], data[high_index] = data[high_index], data[low_index]
print(data)
+1

Mark this one out.

>>> sorted(student_tuples, key=itemgetter(2), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
-2
source

All Articles