使用基数排序在数组python中查找字谜

时间:2018-08-10 08:34:32

标签: sorting

我现在正在研究基数排序,该排序实现分配的计数排序。这个问题让我从给定的数组中找到字谜。我的想法是计算每个单词到一个新数组的数量,而不改变数组的顺序,然后对新数组进行基数排序,这样字谜的索引将存储在我的列表中的同一索引中。这样我就可以轻松找到最大的七字组。我已在Wiki上阅读了基数排序,并了解了基数排序如何用于数字列表。但是,当我尝试使用基数排序对字符串列表进行排序时遇到了一些问题。这是我的代码

def radixsort(array,maxlength):
#sort the whole list and put in to a new array but doest change the index
  newarray=[]
  for i in range(len(array)):
    newarray.append(countsort(array[i]))
#find the index of new array and put in to count
##############
  def listtocount(array,startindex):    
    countarray = [[]for x in range(27)]
    newarray1 = setnewlist(newarray,maxlength)
    for wordindex in range(len(newarray1)):
        if newarray1[wordindex][startindex] == '*':
            countarray[0].append(wordindex)
        else:
            countarray[ord(newarray1[wordindex][startindex])-96].append(wordindex)
    return countarray

  def counttolist(countlist):
    outputarray =[]
    for wordindex in countlist:
        for index in wordindex:
            outputarray.append(array[index])
    return outputarray

  start = maxlength-1
  while start>=0:
    outputlist = counttolist(listtocount(array,start))
    start -= 1
  return outputlist

上面是我的基数排序代码。这是计数排序:

def countsort(array):
"""
a simple count sort
"""
  count = [0] * 26
  for char in array:
    count[ord(char)-97]+=1
  outputlist = ''
  for x in range(len(count)):
    numofoccurrences = count[x]
    for i in range(numofoccurrences):
        outputlist += chr(x+97)

  return outputlist

这是setnewlist函数,它将通过填充“ *”来调整单词的大小

def setnewlist(array,size):
  newlist=[]
  for word in array:
    newstring = ['*'*(size-len(word))]
    newlist.append(''.join(newstring)+''.join(word))
  return newlist

我的问题是运行代码后,基数排序无法正常工作。例如,如果我输入了array = ["apple","australia","algorithm","sell","olympic","jack","sleep","aplpe","alppe"], 程序输出['apple', 'sell', 'olympic', 'jack', 'sleep', 'aplpe', 'alppe', 'australia', 'algorithm'] 我真的可以帮忙。

0 个答案:

没有答案