Python Forum
IndexError: list index out of range - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: IndexError: list index out of range (/thread-15423.html)



IndexError: list index out of range - abdullahali - Jan-16-2019

N = 3

# Returns true if square is magic
# square, else returns false.
def is_magic(square):
    # calculate the sum of
    # the prime diagonal
    sum = 0
    for i in range(0, N):
        sum += square[i][i]

        # For sums of Rows
    for i in range(0, N):
        rowSum = 0
        for j in range(0, N):
            rowSum += square[i][j]

            # check if every row sum is
        # equal to prime diagonal sum
        if (rowSum != sum):
            return False

    # For sums of Columns
    for i in range(0, N):
        columnSum = 0
        for j in range(0, N):
            columnSum += square[j][i]

            # check if every column sum is
        # equal to prime diagonal sum
        if (sum != columnSum):
            return False

    return True

str_input = input("write a squence of nine numbers")
str_list = str_input.split()

square = []
for i in range(0, N):
    square.append([])
    for j in range(0, N):
        square[i].append(int(str_list[j + i * N]))

if (is_magic(str_list)):
    print("This is Magic Square")
else:
    print("This is Not a magic Square")
The error I keep getting is in the line where it says
square[i].append(int(str_list[j + i * N]))

I am trying to create a program that asks user for sequence of 9 numbers and determines if they are nagic square or not.


RE: IndexError: list index out of range - nilamo - Jan-16-2019

What's your input? Is it at least 9 numbers long?


RE: IndexError: list index out of range - abdullahali - Jan-16-2019

Yes, i input 123456789 and keep getting that error

(Jan-16-2019, 10:37 PM)nilamo Wrote: What's your input? Is it at least 9 numbers long?

Yes sir, my input is 123456789 for example.


RE: IndexError: list index out of range - perfringo - Jan-17-2019

Shouldn’t this row:

square[i].append(int(str_list[j + i * N]))
be written as:

square[-1].append(int(str_list[j + i * N]))
You create a list named square, append empty list to it and don’t you want append to that last list in square?


RE: IndexError: list index out of range - buran - Jan-17-2019

(Jan-16-2019, 10:53 PM)abdullahali Wrote: Yes sir, my input is 123456789 for example.

>>> '123456789'.split()
['123456789']
>>> '1 2 3 4 5 6 7 8 9'.split()
['1', '2', '3', '4', '5', '6', '7', '8', '9']
>>>
Do you see the problem with your code and the solution for it?