1

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). It is supposed to rearrange a inputted list (say, [3,2,4,1,5]), into, in the example case, [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

1 Answers1

0

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). 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. You also don't do anything with the solved list or orientation input; 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.

Community
  • 1
  • 1
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • Thanks for your comment. The "orient" input is going to be used later, I forgot mentioning that the program is unfinished. Also, the solved list. --- I need it to print "Change q and i" every time it changes q and i (be q and i numbers which are different for each pos input) until pos is arranged in a crescent pattern, that's why I re-made the function. Once again, thank you. – Lucho Pelado Aug 05 '16 at 01:53