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

Python snippet showing weird behaviour

Here’s the code for reference:-

temp = [0 for _ in range(5)]
dp = [temp for _ in range(len(wt)+1)]
        
for i in range(len(wt)):
    for j in range(len(dp[0])):
        print("outside inner loop if statement:",dp,i,j)
        if j-wt[i] >=0:
            print(i,j)
            dp[i][j] = "y"
            print("inside inner loop if statement dp:", dp)

Here’s the relevant output:-

outside inner loop if statement: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] 0 0

outside inner loop if statement: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] 0 1

outside inner loop if statement: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] 0 2

outside inner loop if statement: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] 0 3

outside inner loop if statement: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] 0 4

0 4

inside inner loop if statement dp: [[0, 0, 0, 0, 'y'], [0, 0, 0, 0, 'y'], [0, 0, 0, 0, 'y'], [0, 0, 0, 0, 'y']]

The moment the flow goes in the if block when i=0 and j=4, every fourth column changes to ‘y’ even though the ideal behavior should be dp[0][4] = ‘y’

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

Thanks in advance.

>Solution :

Since temp is stored in dp multiple times you are changing all occurrences of temp when you do dp[0][4] = 'y' so it changes all rows to have ‘y’.

Instead you need:

dp = [[0 for _ in range(5)] for _ in range(len(wt)+1)]
        
for i in range(len(wt)):
    for j in range(len(dp[0])):
        print("outside inner loop if statement:",dp,i,j)
        if j-wt[i] >=0:
            print(i,j)
            dp[i][j] = "y"
            print("inside inner loop if statement dp:", dp)

Because dp = [[0 for _ in range(5)] for _ in range(len(wt)+1)] will re evaluate [0 for _ in range(5)] each time as a different list.

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