Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

max - How to swap maximums with the minimums? (python)

Is there a method to swap the maximum and the minimum of a list?

The list will be as follows and the program has to be continued so that it will print the maximum swapped with the minimum, the second maximum swapped with the second minimum and third maximum swapped with 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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no method for this in python. You can try using primitive methods to build what you want using 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...