Shaggy
Shaggy

Reputation: 1

List indexing troubles

I'm trying to write a function that will return the magic square for any odd number, but don't understand the results I am getting. First the entirety of the list is initialized so that list objects can be overwritten according to the magic square algorithm, and then each number in the range is written to a certain position in the list. The values outputted by the print statements are valid but my return is not.

def magicsquare(n):
    magiclist, placeholders = [], [0]
    for i in range(0, n-1):
        placeholders.append(0)
    for i in range(0, n):
        magiclist.append(placeholders)
    x, y, z = ((n-1)//2), (n-1), 1
    print(x, y, z)
    for i in range(1, (n*n)):
        if i%n != 0:
            magiclist[x][y] = z
            x, y, z = (x+1)%n, (y+1)%n, z+1
            print(x, y, z)
        elif i%n == 0:
            magiclist[x][y] = z
            y, z = y-1, z+1
            print(x, y, z)
    return(magiclist)

magicsquare(3) returns:

1 2 1

2 0 2

0 1 3

0 0 4

1 1 5

2 2 6

2 1 7

0 2 8

1 0 9

Out:[[4, 7, 8], [4, 7, 8], [4, 7, 8]]

For each 3 numbers printed the first two are the two dimensional list position and the third is the number to be inserted into the list at that position, but the function returns these repeating lists no matter how I configure my loops.

Would super appreciate any help. Sorry I'm not savvy to posting a good question.

Upvotes: 0

Views: 58

Answers (1)

Dan D.
Dan D.

Reputation: 74675

All of the lists in the list are the same list. You need to make copies or make each list each time. Compare with:

magiclist = []
for i in range(0, n):
    placeholders = [0]
    for i in range(0, n-1):
        placeholders.append(0)
    magiclist.append(placeholders)

Which is the longer way of writing:

magiclist = [[0 for i in range(0, n-1)] for i in range(0, n)]

Upvotes: 1

Related Questions