Python3經典100道練習題005


題目:輸入三個整數x,y,z,請把這三個數由小到大輸出。
1.程序分析:我們想辦法把最小的數放到x上,先將x與y進行比較,如果x>y則將x與y的值進行交換,然后再用x與z進行比較,如果x>z則將x與z的值進行交換,這樣能使x最小。

【使用冒泡排序】

 1 def mysort1d(a):  #采用冒泡排序
 2     an=len(a)
 3     for i in range(an)[::-1]:
 4         for j in range(i):
 5             if a[j]>a[j+1]:
 6                 a[j],a[j+1]=a[j+1],a[j]               
 7     return a
 8 
 9 a=[int(i) for i in input('please input 3 number: ').split()]
10 print(mysort1d(a))

【網上高手方法】

 1 while 1:
 2     try:
 3         x = int(input("plz input x: "))
 4         y = int(input("plz input y: "))
 5         z = int(input("plz input z: "))
 6         list1 = [x, y, z]
 7         print(sorted(list1))
 8         break
 9     except:
10         print("請輸入整數")

【方法二】

1 print(sorted([int(input("enter a integer: ")) for x in range(3)]))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM