Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading