2016-07-21 52 views
-3

所以我做了一個代碼,要求用戶交換列表中的兩個地方,直到列表從最小到最大。因此,它應該是這樣的:有用戶排序列表從最小到最大

Hello: Your current list is [6, 7, 8, 2 , 9, 10, 12, 15, 16, 17] 
Please pick your first location -> 4 
Please pick your second location -> 2 
Your new list is [6, 2, 8, 7 , 9, 10, 12, 15, 16, 17] 

我已經得到了這部分,但我目前還無法弄清楚如何獲得用戶來進行排序,而不是代碼。

Your list is not sorted: Please continue 
Please pick your first location -> 1 
Please pick your second location -> 2 

Your new list is [2, 6, 8, 7 , 9, 10, 12, 15, 16, 17] 
Please pick your first location -> 3 
Please pick your second location -> 4 

Your new list is [2, 6, 7, 8 , 9, 10, 12, 15, 16, 17] 

Great job, thank you for sorting my list. 

這裏是我的代碼:

list = [4,2,5,5,6,4,7,6,9,5] 
print("Heres your current list", list) 

print("Pick a location between 1 and 10") 
num = int(input()) 
if num <= 10 and num >= 1: 
    print("Please pick another location between 1 and 10") 
    num1 = int(input()) 
    tempBox1 = list[num-1] 
    tempBox2 = list[num1-1] 
    list[num-1] = tempBox2 
    list[num1-1] = tempBox1 
    print("Your new list is", list) 
+0

請[編輯]讓你的縮進是正確的。請使用空格而不是製表符。 –

+0

看起來不錯,爲什麼不對'list'進行排序並將其設置爲像'sorted_list'這樣的變量,並繼續執行您的操作,還要檢查每個用戶輸入,直到列表等於'sorted_list'爲止 – davedwards

+2

使用'list'作爲變量標識符可能會產生誤導。改用'lst','L','my_list'等。 – Tonechas

回答

1

從我能從你的有點混亂的解釋明白,我做了一些很好的編碼這個工作的腳本進行每一個初學者應該學習開始Python和總體規劃的時候。兩個第一個小函數用於避免代碼重複,這樣我可以避免使用所有代碼太長的主函數。

另外,最後一個條件是在您運行任何python腳本時發生的事情(您可以找到關於here的更好的解釋)。

# Function to avoid code repetition 
def verify_index(number): 
    return 1 <= number <= 10 

# Function to ask for the number indexes until they fit the list length 
def input_numbers(): 
    while True: 
     num1 = int(input("Pick a location between 1 and 10: ")) 
     num2 = int(input("Please pick another location between 1 and 10: ")) 
     if verify_index(num1) and verify_index(num2): 
      return num1, num2 

# List and variables defined locally here 
def main_function(): 
    list = [2, 4, 5, 5, 5, 5, 5, 5, 9, 5] 
    print("Heres your current list", list) 
    num1, num2 = input_numbers() 
    while True: 
     print(num1,num2) 
     temp = list[num1-1] 
     list[num1-1] = list[num2-1] 
     list[num2-1] = temp 
     print("Your new list is now: ", list) 
     if list == sorted(list): 
      break 
     num1, num2 = input_numbers() 
    print("Congratulations! Your list is now sorted by your commands!") 

# Code your script will execute once is run 
if __name__ == '__main__': 
    main_function() 

如有任何疑問或疑問,隨時提問。

(編輯:用戶TesselatingHecker固定一個更好的模式verify_index功能,建議)

+0

一件小事就是允許'list'具有不同的長度,而不是對'1-10'範圍進行硬編碼並使用'len()'而不是 – mitoRibo

+0

@rbierman是的的確如此。也可以更改可能有衝突/誤導性的列表變量標識符。謝謝 –

+0

第一個函數'verify_index'是'if(true)return true else else return'的反模式,可以直接返回1 <= number <= 10'。但是你可以擺脫它,並用'if 1 <= num1 <= 10'替換'如果verify_index(num1)',它將表現相同甚至更少的字符。 – TessellatingHeckler

相關問題