Sami
Sami

Reputation: 486

Can't swap the elements in a list, Python

I am trying to swap elements in a list using while loop. So that the function can only swap two consecutive elements at a time. And return me with the possible list in a list, But it's only printing one possible path.

The initial list is[4,3,2,1]

Expected Output = [[3,4,2,1], [4,2,3,1],[4,3,1,2]]

Current Output = [[3,2,1,4],[3,2,1,4],[3,2,1,4]]

My code is

array = [4,3,2,1]

def possible_paths(Array):
    temp_arr = []
    i=0
    while i < (len(Array) -1):
        temp1 = Array[i]
        Array[i] = Array[i+1]
        Array[i+1] = temp1
        temp_arr.append(Array)
        i = i+1
    return temp_arr

arr1 = []
poss = possible_paths(array)
arr1.append(poss)
print(arr1[:])

Upvotes: 0

Views: 312

Answers (2)

Arunav MAHESHWARI
Arunav MAHESHWARI

Reputation: 134

I think that what you're looking for is:

array = [4,3,2,1]

def possible_paths(arr1):
    temp_arr = []
    i=0
    while i < (len(arr1) -1):
        nextpath = arr1[:]
        nextpath[i], nextpath[i+1] = nextpath[i+1], nextpath[i]
        temp_arr.append(nextpath)
        i += 1
    return temp_arr

arr2 = possible_paths(array)
print(arr2[:])

The same list was getting edited and switched again and again. Also, there is no need for the variable temp1; you can just use multiple variable assignment through tuples. You accidentally made arr1 an array of an array of arrays; temp_arr is already an array of arrays, so there is no need to put it inside another array. "i += 1" is just shorthand for "i = i+1". It is better to use arr1 as the function variable, as capital letters aren't usually used for naming.

Upvotes: 3

bala.alab
bala.alab

Reputation: 66

array = [4,3,2,1]
def possible_paths(Array):
    temp_arr = []
    i=0
    while i < (len(Array) -1):
        clone_array = Array[:]
        clone_array[i], clone_array[i+1] = clone_array[i+1], clone_array[i]
        temp_arr.append(clone_array)
        i = i+1
    return temp_arr

poss = possible_paths(array)
print(poss)

Output : [[3, 4, 2, 1], [4, 2, 3, 1], [4, 3, 1, 2]]

Upvotes: 2

Related Questions