0

嘿,所以代码可以完美运行,非常感谢!

我还有一个问题。我想在两个列之间显示一个箭头。我创建了这段代码,但我真的不知道如何让它进入正在切换的列之间。有什么建议么?

def arrow(lst, i):                 # function for the arrow
if (lst[i], lst[i+1] == lst[i+1], lst[i]):
    t.home()
    t.penup()
                     # im thinking something goes here but i dont know what :P
    t.pendown()
    t.pencolor("red")
    t.right(90)
    t.forward(20)

任何帮助将不胜感激!谢谢!顺便说一句,其余代码就像 imran 的代码!:) 谢谢你!

4

3 回答 3

1

从您的原始代码中只需要编辑一些东西,最好有两个 for 循环来检查它的值。同样,在您这样做之前[i-1],它会破坏冒泡排序的目的,因为如果这有意义的话,您是从左到右排序的。无论如何,这就是我所做的。

def swap(lst):
    for i in range (len(lst)):
        for j in range (len(lst)-1):
            if lst[j] > lst[j+1]:
                lst[j], lst[j+1] = lst[j+1], lst[j]
                print (lst)


lst = input("Enter list to be sorted: ")
print (lst)
swap(lst)
于 2013-04-10T04:24:25.420 回答
1

我根据您的代码编写了冒泡排序:

import types

def bubble_sort(lst):
    assert(type(lst)==types.ListType)
    for index in range(1,len(lst)):
        while index > 0 and lst[index-1] > lst[index]:
            lst[index-1] , lst[index] = lst[index] , lst[index-1]
            index -= 1
    return

lst = input("Enter list to be sorted: ")
print "Original: ",lst
bubble_sort(lst)
print "Sorted: ",lst

测试看起来像:

C:\Users\NAME\Desktop>bubble.py
Enter list to be sorted: [4, 24, 25, 2, 6, -1, 73, 1]
Original:  [4, 24, 25, 2, 6, -1, 73, 1]
Sorted:  [-1, 1, 2, 4, 6, 24, 25, 73]

希望能帮助到你!

于 2013-04-10T04:16:24.540 回答
0

您的代码看起来很像这里的冒泡排序版本之一。您的版本不起作用的主要问题是因为您将索引 i 处的 lst 与 i-1 进行比较,当 i=0 时失败。将该部分更改为:

        if (lst[i] < lst[i + 1]):
            swapped = False
            lst[i+1], lst[i] = lst[i], lst[i+1]

另外,不要在函数之外定义 n (理想情况下应该称为bubble_sort,或类似的东西),这是糟糕的编程,一个等待发生的错误。我不知道你想用什么来完成lst = [lst]。可能想要使用不同的变量名。

编辑: 我对您的代码进行了一些自由更改。我把所有的绘图调用都放在了冒泡排序中。冒泡排序还在内部将列表转换为元组列表,其中元组的第二个元素是颜色。代码末尾的 for 循环没有做任何有价值的事情。我认为您的主要问题是它没有在 while 循环的每次迭代之间暂停,因此您看不到列表中的元素冒泡。

#!/usr/bin/python
import turtle as t

def draw(lst, width):
  for x in lst:
    height = x[0]
    t.color(x[1])
    t.forward(width)
    t.left(90)
    t.forward(height)
    t.left(90)
    t.forward(width)
    t.left(90)
    t.forward(height)
    t.left(90)
    t.penup()
    t.forward(30)
    t.pendown()

def bubble_sort(orig_lst):  
  lst = [ (x, "blue") for x in orig_lst ]
  n = len(lst)-1 
  t.pensize(3)
  draw(lst, width)
  swapped = True  
  while swapped:  
    swapped = False  
    for i in range(n):  
        if lst[i+1][0] < lst[i][0]:  
            lst[i], lst[i+1] = lst[i+1], lst[i]
            lst[i] = (lst[i][0], "green")  
            swapped = True 
            next = raw_input("hit any key to continue ")
            t.home()
            t.clear() 
            draw(lst,width)
  newLst = [ x[0] for x in lst ]
  return newLst

# TOP LEVEL
original_lst = input("Enter list to be sorted: ")
width = input("Provide the width: ")

newLst = bubble_sort(original_lst)
print "Done! Sorted list is: ", newLst
next = raw_input("hit any key to exit ")
于 2013-04-10T04:15:06.213 回答