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
330 views
in Technique[技术] by (71.8m points)

python - Sorting three numbers in ascending order without using functions

One of my assignments is to write a python program that sorts three numbers in ascending orders without use of any functions like sort or swap.

This is the first thing I came up with:

a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
if a < b:
    if b < c:
        print (a, "<", b, "<", c)
    else:
        if a < c:
            print (a, "<", c, "<", b)
        else:
            print (c, "<", a, "<", b)
else:
    if c < b:
        print (c, "<", b, "<", a)
    else:
        if c < a:
            print (b, "<", c, "<", a)
        else:
            print (b, "<", a, "<", c)

My teacher said to try and simplify it so I wrote this next (which basically is a roundabout way to use swap):

a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
if a > c:
    a = a + c
    c = a - c
    a = a - c  
if a > b:
    a = a + b
    b = a - b
    a = a - b
if b > c:
    b = b + c
    c = b - c
    b = b - c
print (a, "<", b, "<", c)

So I guess my question is whether it can be more simplified than this and what that would look like.


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

1 Reply

0 votes
by (71.8m points)

I think using your approach in the second code, this is the easiest way out:

a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))

if a > b:
    a,b = b,a
if a > c:
    a,c = c,a
if b > c:
    b,c = c,b
    
print (a, "<", b, "<", c)

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

...