2016-12-16 9 views
0
doc = "unsorted.txt" 
out_fil = "H:\Grade 11\Intro to Computer Science\sorted.txt" # Used in the Windows variation of the program 
out_file = "/Applications/Banter" # Used in the Mac variation of the program 
import time 
def main(): 
    order = False 
    blank = [] 
    passcount = 0 
    starttime = time.time() 
    numlist = CreateList(doc) 
    while not order: 
     passcount = passcount + 1 
     switch = False 
     switchcount = 0 
     print "1" # These are test prints to I used to find problems 
     for x in range (len(numlist)): 
      print "2" # These are test prints to I used to find problems 
      if numlist[x] > numlist[x+1]: 
       temp = numlist[x+1] 
       numlist[x+1] = numlist[x] 
       numlist[x] = temp 
       switchcount = switchcount + 1 
       switch = True 
       print "9" # These are test prints to I used to find problems 
      elif switch == 0: 
       order = True 


    CreateFile(numlist) 
    endtime = time.time() 
    print "This list required",endtime-starttime,"seconds to sort." 
    print "This list required",switchcount,"switches to sort." 
    print "This list required",passcount,"passes to sort." 



def CreateList(doc): 
    sort = open(doc,"r") 
    numlist = sort.readlines() 
    sort.close() 
    for x in range (len(numlist)): 
     numlist[x] = int(numlist[x].strip()) 
    return numlist 

def CreateFile(numlist): 
    sort = open(doc,"w") 
    sort.write(str(numlist)+"\n") 
    sort.close() 
    return numlist 

def List(numlist): 
    print numlist 

main() 

私のプログラムの主な目的は、バブルソート方法を使用してファイルから整数のリストをソートし、そのリストを新しいファイルに入れることです。また、これを実行するのにかかる時間と、プログラム内のパスとスイッチの数を完全に並べ替えるために要した時間についても詳しく説明します。バブルソートと範囲外リストの索引の使用

私が抱えている問題は、リストインデックスが範囲外になることです。これは、numlistのxとx + 1を比較しているためです。しかし、リスト内で互いに隣り合う2つの整数をソートするために、x + 1を比較する必要があります。リスト内のすべての整数を比較し、x + 1のためリストにない空間を比較しようとしないようにプログラムを修正できる方法はありますか?

+0

FYIでは、「temp = numlist [x + 1]; numlist [x + 1] = numlist [x]; numlist [x] = temp'の3行を合理化してnumlist [x]、numlist [ x + 1] = numlist [x + 1]、numlist [x] 'である。これは、明示的に一時変数を作成する必要性をなくす素晴らしい1ライナーです。 (一時的なタプルが右側のシーンの背後に作成され、展開され、左側に割り当てられます。Google Pythonのタプルは、さらに解凍します)。 –

答えて

1

あなたはこの方法であなたのループを作ることができる:

for x in range (len(numlist) -1): 
0

stackoverflowのが答えのための素晴らしいリソースですが、宿題のためにそれらを放棄することは不正行為のように感じています。私はあなたの半分の方法であなたを満たすでしょう:あなたのループをより少ない反復で実行させる。

関連する問題