于是在Wikipedia上找到了如下伪代码:
function oddEvenSort(list) {
sorted = false;
while(!sorted)
{
sorted = true;
for(i = 1; i < list.length-1; i += 2)
{
if(list[i] > list[i+1])
{
Swap list[i] and list[i+1]
sorted = false;
}
}
for(var i = 0; i < list.length-1; i += 2)
{
if(list[i] > list[i+1])
{
Swap list[i] and list[i+1]
sorted = false;
}
}
}
}
我正在尝试用 Python 编写它:
def oddEvenSort(List):
sorted = False
while not sorted:
sorted = True
for (i == 1 and i < List.length-1 and i == i+2): #getting a syntax error here
if (List[i] > List[i+1]):
List[i], List[i+1] = List[i+1], List[i]
sorted = False
for (i == 0 and i < List.length-1 and i == i+2):
if (List[i] > List[i+1]):
List[i], List[i+1] = List[i+1], List[i]
sorted = False
def main():
x = input("Please enter a list of numbers: ")
y = oddEvenSort(x)
print(y)
main()
但是,我在这段代码中遇到了几个错误。我怎样才能删除它们?
请您参考如下方法:
您上面的代码中存在一些问题。我将解决所有问题:
- 编写for循环并使用迭代
- 从函数返回
- 不隐藏内置函数的最佳做法
- 解析输入
编写循环和迭代:
for(i = 1; i < list.length-1; i += 2)
写成(在 Python 中):
for i in range(1, (len(list) - 1), 2)
参见:range()
从函数返回:
您的函数 oddEvenSort() 也不返回任何内容。
因此 y = oddEvenSort(...) 将返回 None。您需要在函数末尾有一个返回列表。
不隐藏内置函数:
不要使用名为 list 的变量隐藏内置类型和函数,例如 list()。使用 xs 或更合适的名称。
解析输入:
感谢乔兰·比斯利;是的,您的输入 格式不正确(还)。尝试通过执行以下操作将其转换为整数列表:
s = input("Enter some numbers (comma separated):")
xs = [x.strip() for x in s.split(",")] # clean input
ys = list(map(int, xs)) # map input list into actual integers
