所以我在维基百科上发现了以下伪代码:
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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图用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()
Run Code Online (Sandbox Code Playgroud)
但是,我在这段代码中遇到了一些错误.我该如何删除它们?
您的代码中存在一些问题.我将解决所有问题:
编写循环和迭代:
for(i = 1; i <list.length-1; i + = 2)
写成(在Python中):
for i in range(1, (len(list) - 1), 2)
Run Code Online (Sandbox Code Playgroud)
看到: range()
从函数返回:
你的功能oddEvenSort()也没有返回任何东西.
所以y = oddEvenSort(...)会回来None.你需要return list在函数的末尾.
NOT Shadowing内置插件:
请勿隐藏内置类型和函数,例如list()名为变量的变量list.使用xs或更合适的名称.
解析输入:
感谢Joran Beasley; 是的,你input的表格形式还不正确.尝试通过执行以下操作将此转换为整数列表:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |