我正在做另一个考试问题,剪下的代码如下:
def reverse(a):
i=0
while i < len(a):
j = len(a) - 1
tmp = a[i]
a[j] = tmp
a[i] = a[j]
i = i +1
a = sys.argv
reverse(a)
print " ".join(a)
提出的一个问题是你发现了5个错误。我找到了5个中的3个但是当我试图找到最后两个但我的代码没有完全排序列表。 例如,如果你打“1”,“2”,“3”就会打印“3”,“1”,“2”
我对以上代码的编辑:
import sys #error 1
def reverse(a):
i = 0
while i < len(a):
j = len(a[i])-1 #error 2
tmp = a[i] #I know its either this one or the two below...
a[i] = a[j]
a[j] = tmp
i = i +1
a = sys.argv[1:]# error 3
reverse(a)
print " ".join(a)
我不能使用python中的任何内置函数,例如“.sort()”
答案 0 :(得分:1)
def reverse():
i = 0
while i < int(len(a) / 2):
j = len(a) - 1 - i
tmp = a[i]
a[i] = a[j]
a[j] = tmp
i = i + 1
反向算法应该做类似的事情,交换1-5,2-4然后停止。
对于5元素输入,您只需要进行2次交换。当您在迭代输入时j
向前移动时,i
也应向后移动。
由于您没有从方法返回任何内容并修改全局a
,因此您不需要参数。
BTW,在Python中,您可以使用交换元素而不是使用tmp
变量。
a[i], a[j] = a[j], a[i]