Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
924 views
in Technique[技术] by (71.8m points)

artificial intelligence - Index 1 is out of bounds for axis 0 in size 1 in Python

For a university assignment I was asked to convert a 1 line text file into a 2d array. However, when I run the program, I get this error:

(venv) D:Uni StuffYear 2AIGPAssignmentPYTHONASSIGNMEN>python astar.py
Input file name: Lab9TerrainFile1.txt
Traceback (most recent call last):
  File "D:Uni StuffYear 2AIGPAssignmentPYTHONASSIGNMENastar.py", line 129, in <module>
    main()
  File "D:Uni StuffYear 2AIGPAssignmentPYTHONASSIGNMENastar.py", line 110, in main
    number_of_rows = maze_file[1]
IndexError: index 1 is out of bounds for axis 0 with size 1

This is the code for generating the maze:

def main():

    maze_file = open(input("Input file name: "), "r").readlines()

    maze_file = np.array([maze_file])

    number_of_columns = maze_file[0]

    number_of_rows = maze_file[1]

    maze_column = np.array_split(maze_file[2:8], number_of_columns)

    maze_row = np.array_split(maze_file[2:8], number_of_rows)

    maze = np.concatenate([maze_column][maze_row])

    start = np.where(maze == 2)

    end = np.where(maze == 3)

    maze_file.close()

    path = astar(maze, start, end)
    print(path)

Any help would be appreciated and thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can test this by checking the size of your array maze_file by running the code below.

print(len(maze_file))

If it returns 1, then it means it only has 1 element.

maze_file[0] means you are getting the first element. Hence, the index 0 between the square brackets. When you specify maze_file[1], its trying to get the 2nd element, which doesn't exists. Hence the error Index out of Bounds.

Reviewing your code, it looks like you are trying to get the number of columns and rows for the array. You can use the following code.

number_of_columns = len(maze_file)
number_of_rows = len(maze_file[0])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...