2014-04-13 150 views
0

我只是寫另一個基數排序程序,這裏是我的代碼:蟒蛇循環排序

#----------radix sort---------- 
def set_output(): 
    output_list = [] 
    for i in range (10): 
     output_list.append(queue()) 
    return output_list 

def set_radix(lists): 
    output_list = set_output() 
    for queue in lists: 
     for num in queue: 
      a = num[2] 
      output_list[int(a)].add(num) 
    return output_list 

def sec_radix(input_list, i): 
    output_list = set_output() 
    for queue in input_list: 
     while len(queue) > 0: 
      num = queue.after() 
      a = num[i] 
      output_list[int(a)].add(num) 
    return output_list 

def done_radix(num_list): 
    return sec_radix(sec_radix(set_radix(num_list), 1), 0) 

蟒蛇殼不斷告訴我說:「IndexError:字符串索引超出範圍」,我的數字串好吧。我認爲我的def set_radix()函數有問題,但我找不到它在哪裏?

+2

你會得到哪個錯誤? – sshashank124

+0

該隊列不應該大寫? – ojblass

+0

運行一些代碼是不可能的。另外,我不知道從哪裏開始運行它* – Veedrac

回答

2

這是一個基數排序編碼,以便合理的人可以理解它。我從here中偷走了它的大部分。

def radixsort(aList): 
    RADIX = 10 
    maxLength = False 
    tmp , placement = -1, 1 

    while not maxLength: 
    maxLength = True 
    # declare and initialize buckets 
    buckets = [list() for _ in range(RADIX)] 

    # split aList between lists 
    for i in aList: 
     tmp = i // placement 
     print ("i is " , i) 
     print ("placement is " , placement) 
     print ("tmp is ", tmp) 
     print ("tmp % RADIX is ", tmp % RADIX) 
     buckets[tmp % RADIX].append(i) 
     if maxLength and tmp > 0: 
     maxLength = False 

    # empty lists into aList array 
    a = 0 
    for b in range(RADIX): 
     buck = buckets[b] 
     for i in buck: 
     aList[a] = i 
     a += 1 

    # move to next digit 
    placement *= RADIX 
    return aList 



a = radixsort([18,5,100,3,1,19,6,0,7,4,2]) 
print(a) 

我從網站上獲得的代碼中有一些問題產生於產生浮動的%。我懷疑從python 2到3的差異。