Home > database >  How is this getting first value same from 2nd repeat?
How is this getting first value same from 2nd repeat?

Time:06-25

def solution(A):
    A_inp = A
    roated_a =list(range(len(A_inp)))
    
    k=1
    while k < 3:
        for i in range(len(A_inp)-1):
            
            roated_a[i 1] = A_inp[i]
            roated_a[0] = A_inp[len(A_inp)-1]
            
        A_inp = roated_a
        k =1
        print(roated_a)
        

inp_arr = [int(item) for item in input("Enter the list items : ").split()]
solution(inp_arr)

This code should rotate the input array. Input given : 3 6 8 7 Expected Output should be : 7 3 6 8 ; 8 7 3 6; 6 8 7 3 But I am getting : 7 3 6 8 ; 7 7 7 7 ; 7 7 7 7

How is it getting the 7 for all the index after first iteration ? Where is the error ? Can anyone help ?

CodePudding user response:

A_inp = roated_a makes both variable names to refer the same object. So, when you update roated_a, you also change A_inp, starting 2nd iteration.

The fix (if you decide to stick with this implementation) is to make an actual copy:

A_inp = roated_a.copy()

CodePudding user response:

You can rotate the list as follows to get the correct output:

def solution(A):
    for i in range(1, 4):
        print(A[i:]   A[:i])

inp_arr = [3, 6, 8, 7]
solution(inp_arr)

Output:

[6, 8, 7, 3]
[8, 7, 3, 6]
[7, 3, 6, 8]
  • Related