1

I am trying to iterate over a multidimensional numpy array while trying to solve one of the Project Euler problems. The problem requires finding the largest product of four adjacent numbers in a 20x20 grid. For now, I am just testing to see if my code is grabbing four adjacent numbers, going left to right horizontally:

arr1 = np.array([[8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8], 
                 [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
                [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65]])


 for row in arr1:
    checklist = []
    m = 0
    n = 4
    while n <= 20:
        checklist.append(row[m:n])

        m += 1
        n += 1

print(checklist)

The returned checklist is:

[array([81, 49, 31, 73]), array([49, 31, 73, 55]), array([31, 73, 55, 79]), array([73, 55, 79, 14]), array([55, 79, 14, 29]), array([79, 14, 29, 93]), array([14, 29, 93, 71]), array([29, 93, 71, 40]), array([93, 71, 40, 67]), array([71, 40, 67, 53]), array([40, 67, 53, 88]), array([67, 53, 88, 30]), array([53, 88, 30,  3]), array([88, 30,  3, 49]), array([30,  3, 49, 13]), array([ 3, 49, 13, 36]), array([49, 13, 36, 65])]

This is what I was looking for, but it's only grabbing the last row of the array. Why are the first two rows being skipped?

2 Answers 2

1

You are declaring checklist variable inside the for loop. That's why in each iteration of for loop, checklist variable is being reset to [ ]. Hence it is keeping data only of the last iteration of for loop i.e. last row of arr1.

You should declare checklist above the for loop.

Sign up to request clarification or add additional context in comments.

Comments

1

The checklist variable is being reset inside the for loop on each iteration. Move the declaration above the for loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.