当前位置:网站首页>Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.

Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.

2022-07-05 08:22:00 Lazy smile

example 005: Three number order

subject : Enter three integers x,y,z, Please output these three numbers from small to large .

  Method 1 :

#  Loop through each number , Compare two numbers , If the former number is greater than the latter number, the two numbers will exchange positions 
#  Enter three numbers and save to raw in 
raw = []
for i in range(3):
    x = int(input('int%d: ' % (i + 1)))
    raw.append(x)
#  Loop through each number , Compare two numbers , If the former number is greater than the latter number, the two numbers will exchange positions 
for i in range(len(raw)):
    for j in range(i, len(raw)):
        if raw[i] > raw[j]:
            raw[i], raw[j] = raw[j], raw[i]
print(raw)
int1: 3
int2: 2
int3: 6
[2, 3, 6]

 

Method 2 :

Call the sort function directly sorted()

#  Enter three numbers and save to raw2 in 
raw2 = []
for i in range(3):
    x = int(input('int%d: ' % (i + 1)))
    raw2.append(x)
#  Direct call function sorting 
print(sorted(raw2))
int1: 5
int2: 7
int3: 3
[3, 5, 7]

 

原网站

版权声明
本文为[Lazy smile]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050816109818.html