简体   繁体   English

重新安排数组交换2的Python程序不起作用,有人可以帮助我吗?

[英]Python program for rearranging an array swapping 2 at a time doesn't work, could someone help me?

This is the code I've written for a Python program (please keep in mind that I learnt Python from the Internet a couple of days ago). 这是我为Python程序编写的代码(请记住,我几天前从Internet上学过Python)。 It is supposed to rearrange a inputted list (say, [3,2,4,1,5]), into, in the example case, [1,2,3,4,5]. 在示例情况下,应该将输入的列表(例如,[3,2,4,1,5])重新排列为[1,2,3,4,5]。 For some reason, it's not working, and I can't figure the reason out. 由于某种原因,它不起作用,我无法弄清楚原因。 I've tried many different ways to do it, but none is working. 我尝试了很多不同的方法,但没有一种方法可行。 In this case, the program returns the same value as the original one. 在这种情况下,程序返回与原始值相同的值。 Here's the code: 这是代码:

    #General purpose string solver (by 2swapping + sune combos)
def solvepermutation():
    #Setup
    global pos
    pos = raw_input('Ingrese permutacion.\n')
    orientation = raw_input('Ingrese orientacion.\n')
    #Generating solved position
    solved=[]
    for i in range(len(pos)):
        solved.append(int(i+1))
    #Solving pos
    solvepos()
    #Printing pos solved
    print(pos)

#Function which solves pos
def solvepos():
    global pos
    for z in range(len(pos)-1):
        for q in range(len(pos)):
            if pos[z] == q+1:
                pos[z],pos[q]=pos[q],pos[z]
                continue
            else:
                continue

solvepos() operates on the global pos , but that's a string - when you do if pos[z] == q+1: , q+1 is an integer (one of the values from the range ), but pos[z] is a string (one of the characters of the input). solvepos()操作,并且在global pos ,但是这是一个字符串-当你做if pos[z] == q+1: q+1是一个整数(从值的一个range ),但pos[z]是一个字符串(输入的一个字符)。 These will never compare equal, so no swap occurs. 这些永远不会相等,所以不会发生交换。

There are many things that are wrong with this code, starting with the fact that sort is built in and it does no good to re-implement it. 这段代码有很多问题,首先是内置了sort ,重新实现它是没有用的。 You also don't do anything with the solved list or orientation input; 您也不会对已solved列表或orientation输入执行任何操作; and you should be using parameters and return values instead of trying to communicate through global variables. 你应该使用参数和返回值,而不是尝试通过全局变量进行通信。 But most importantly, don't iterate like that . 但最重要的是, 不要那样迭代

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM