def kindDetector(list):
for i in range(0,len(list)):
if type(list[i]) != type('a'):
return 0
return 1
def findWords(list,i):
if i == 0:
return list[0]
if list[i] < findWords(list,i-1):
return list.pop(i)
else:
return list.pop(i-1)
def sortWords(list,i):
result=[]
while i >= 0:
result.append(findWords(list,i))
i -=1
print(result)
list = input('Enter your words, with a space between.\t').split()
i = len(list)-1
if kindDetector(list):
sortWords(list,i)
但在这里,我只能输入2个单词,当我尝试使用3时,会发生这种情况:
Traceback (most recent call last):
File "C:/Users/honey/Desktop/python/selfMade/sortWords.py", line 26, in <module>
sortWords(list,i)
File "C:/Users/honey/Desktop/python/selfMade/sortWords.py", line 18, in sortWords
result.append(findWords(list,i))
File "C:/Users/honey/Desktop/python/selfMade/sortWords.py", line 10, in findWords
if list[i] < findWords(list,i-1):
IndexError: list index out of range
您将BubbleSort与SelectionSort混合(即,比较相邻项并尝试一次移动一个,直到列表排序为止)(即,从未排序的列表中找到最小的项,并将其附加到结果列表的前面)。你知道吗
这里还有一些问题:
Python通过引用传递变量,这意味着函数接收原始列表的句柄而不是副本。如果您在迭代时更改列表(您的
pop()
调用所做的),您将遇到索引错误。你的
findWords
函数有缺陷。从后向前迭代,并检查当前元素是否在词典上比其前一个元素小(即leftneighbor)。您可能想将pop
调用更改为return
语句,是吗?我已经很快实现了一些基本的排序算法(没有错误处理、类型比较器的使用等):
看看它们,试着理解它们,并在网上阅读这三种技巧。然后尝试使用自己的函数重新实现它们。享受编码的乐趣:)
相关问题 更多 >
编程相关推荐