2014-04-20 20 views
0

我是新來的Python,我試圖要求用戶提供一些需要的元素,然後要求在單獨的行中輸入每個元素,然後對該輸入進行氣泡排序。如何指定輸入的數量以及如何獲取每個輸入的新行?

import readline 
def bubbleSort(alist): 
    for passnum in range(len(alist)-1,0,-1): 
     for i in range(passnum): 
      if alist[i]>alist[i+1]: 
       temp = alist[i] 
       alist[i] = alist[i+1] 
       alist[i+1] = temp 

alist = readlines('Enter the list to sort \n', 'r').rstrip() 
alist = alist.split(',') 

bubbleSort(alist) 
print alist.readlines() 

如果我改變readlinesraw_input,代碼工作,但輸入進去只有一行。有人可以幫我解釋如何指定元素的數量,以及如何讓每一個輸入成爲新行?

回答

0

的Python 3:

def bubbleSort(alist): 
    for passnum in range(len(alist)-1, 0, -1): 
     for i in range(passnum): 
      if alist[i] > alist[i+1]: 
       temp = alist[i] 
       alist[i] = alist[i+1] 
       alist[i+1] = temp 
    return alist 

def main(): 
    lines = [] 
    print("Enter names (hit enter twice to bubble-sort):") 
    while True: 
     line = input("%3i: " % (len(lines)+1)) 
     if not line: 
      break 
     lines.append(line) 
    print("Sorted names:") 
    for i, name in enumerate(bubbleSort(lines), 1): 
     print("%3i. %s" % (i, name)) 

main() 

輸入輸出:

Enter names (hit enter twice to bubble-sort): 
    1: Mark 
    2: Jim 
    3: Kayne 
    4: Foobar 
    5: Zulu 
    6: Anna 
    7: Yeti 
    8: 
Sorted names: 
    1. Anna 
    2. Foobar 
    3. Jim 
    4. Kayne 
    5. Mark 
    6. Yeti 
    7. Zulu 
+0

當我試着運行你的代碼,它運行但沒有給出任何輸出,甚至要求一個輸入 – user3467152

+0

你是否在python 3k環境中運行它?對於py 2.x,用'raw_input'替換'input'。 – CoDEmanX

+0

我已經替換了它,仍然沒有給出任何東西 – user3467152

1

我相信這是你要找的東西的基礎知識。

ntimes = raw_input("Enter the number of lines") 

ntimes = int(ntimes) 

alist = [] 

while (ntimes > 0): 
    ntimes -= 1 
    alist.append(raw_input('Enter the list to sort \n').split(',')) 

print alist 
+0

嗨,你的建議工作正常,獲取每個輸入在一條線上,但是基於其輸入一些如何開始打印的元素訂單不鼓泡他們 – user3467152

+0

更改打印alist打印bubbleSort(alist) – Amazingred

+0

我已經改變它,現在它給出了一個「無」輸出 – user3467152

2

試試這個:

bubbleSort([raw_input('Enter element') for _ in range(input('Enter the number of elements needed'))]) 

這一個班輪應該做的伎倆

EXPLAIN :::

本質上講,我們在這裏做的三件事情,一旦你撤消列表理解和pythonic格式。

#Asking for the number of elements needed and making a loop that will repeat that many times 
for _ in range(input('Enter the number of elements needed')): 

    #in each loop, retrieve an element from the user and put it into a list for later 
    listvariable.append(raw_input('enter element')) 

#Then at the end we're taking that list and putting it through the bubbleSort 
bubbleSort(listvariable) 

在上面的一行解決方案中使用列表理解簡化了代碼。

相關問題