[英]Python error with a bubble sort function
由於某種原因,由於該功能,我會出錯,並且無法弄清楚它出了什么問題。
def bubbleSort(lis):
for pas in lis:
for i in pas:
if lis[i] > lis[i+1]:
lis[i],lis[i+1] = lis[i+1],lis[i]
我收到以下錯誤:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
bubbleSort(hello)
File "C:/Users/albert/Desktop/test.py", line 4, in bubbleSort
for i in pas:
TypeError: 'int' object is not iterable
假設lis
是一個整數列表,則pas
將是一個整數。 for i in pas:
失敗,因為單個整數中沒有i
。
冒泡排序通常是通過在發生任何更改時進行的外部循環以及對n-1
索引而不是列表元素進行迭代的內部循環來完成的。 您可以在許多地方找到標准實現,這是Rosetta代碼1 :
def bubble_sort(seq):
"""Inefficiently sort the mutable sequence (list) in place.
seq MUST BE A MUTABLE SEQUENCE.
As with list.sort() and random.shuffle this does NOT return
"""
changed = True
while changed:
changed = False
for i in xrange(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
return None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.