【问题标题】:Python why does out of bounds keep changing with every iteration?Python为什么每次迭代都会越界?
【发布时间】:2018-12-20 03:15:33
【问题描述】:

每次我运行程序时,它似乎都会在不同的位置超出范围,我不知道为什么。我非常接近完成这部分,这让我发疯。有人可以在他们的机器上运行它并让我知道他们的想法吗?我试图用不同的 if 语句来控制边界,但一段时间后它变成了一堆废话。

import os.path
import random
import math
import sys
import os
import re



pd = [ #This is the visual of the pyramid

[                 1                    ], #[0][0]  row and total col# ex [2][1] = 5
[              2,    3                 ], #[1][1]
[            4,   5,    6,             ], #[2][2]
[         7,   8,    9,   10,          ], #[3][3]
[      11,  12,   13,  14,   15,       ], #[4][4]
[    16,  17,   18,  19,  20,    21,   ], #[5][5]

]

#The list used to store visited nodes
dots_list = [[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21]]



#Do not remove this sentence

TOTAL_NUMBERS = 21 # the total numbers in the pyramid
x = 0          # represents left and right direction in pd -- adding goes right, subtracting goes left
y = 0          # represents up and down direction in pd -- adding goes down, subtracting goes up
lower_bound = 1 # used as lower bound in dice selection
upper_bound = 4 # used as upper bound in dice selection
move_counter = 0 # used to count the total number of moves made in game

print("Starting position: ",pd[y][x])  # The starting position used for debugging
start_position = pd[y][x] # The starting point of the game [y][x] up/down y, left/right x set at 1, the top of pyramid
dots_list[start_position - 1].append('.') # Adds dot to number one to indicate start of game
move_counter  += 1 #this counts as a move

# ----  loop begin ----
print('begin loop')
print('------------------------------------------------------------------')
while any(len(m) < 2 for m in dots_list):

    random_roll = random.randint(upper_bound-2, upper_bound) # Randomly selects a number from 1 to 4 to be used as fair die roll
   # debugging output removing will cause errors
    if random_roll == 1:
        print("Upper left Roll: " ,random_roll)
        print('X is:', x)
        print('Y is:', y)
        print()

        if pd[y][x] == 1 or pd[y][x] == 2 or pd[y][x] == 4 or pd[y][x] == 7 or pd[y][x] == 11 or pd[y][x] == 16:
            # print('Invalid Direction --  Move Count Increased')
            print('------------------------------------------------------------------')
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
            print()
            move_counter += 1
        else:
            if y > 0:
                new_pos = pd[y - 1][x - 1]
                y -= 1
                x -= 1
                # print('x: ', x, 'y:', y)
                # print('upper left new pos: ' , new_pos)
                # print('------------------------------------------------------------------')
                start_position = pd[y - 1][x - 1]
                # print('st pos', start_position)


            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
            print('Rolling again')



    elif random_roll == 2:
        print("Upper right Roll: ", random_roll)
        print('X is:', x)
        print('Y is:', y)
        print('moving the next element before changes')
        print()

        if y > 5:
            y-=1
        if x > 5:
            x-=1
        if y > 3:
            y-=1

        if y > x:
            new_pos = pd[y][x]
            start_position = new_pos
            print('new start_pos', start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
        print('X is:', x)
        print('Y is:', y)
        print("after changes")

        start_position = new_pos
        print('new start_pos', start_position)
        dots_list[start_position - 1].append('.')
        for i in range(len(dots_list)):
            for j in range(len(dots_list[i])):
                print(dots_list[i][j], end=' ')
            print()

        print()

        if y <= 5 and y > -1 and x > -1 and x <= 5 and x < y:
            if pd[y][x] == 3 or pd[y][x] == 6 or pd[y][x] == 10 or pd[y][x] == 15 or pd[y][x] == 21:
                new_pos = pd[y][x]
                start_position = new_pos
                # start_position = pd[y][x]
                print(' new start_pos', start_position)
                dots_list[(pd[y][x]) - 1].append('.')
                for i in range(len(dots_list)):
                    for j in range(len(dots_list[i])):
                        print(dots_list[i][j], end=' ')
                    print()
                move_counter += 1
                print('Rolling again')
                print()

        else:
            if y > -1 and y < 5:

                print('X is:', x)
                print('Y is:', y)
                print()
                print('moving the next element ')

                y -= 1

                print('X is:', x)
                print('Y is:', y)
                print()
                new_pos = pd[y][x]
                #print('upper right new pos: ', new_pos)
               # print('------------------------------------------------------------------')
                start_position = new_pos
                print(' new start_pos', start_position)
                dots_list[start_position - 1].append('.')
                for i in range(len(dots_list)):
                    for j in range(len(dots_list[i])):
                        print(dots_list[i][j], end=' ')
                    print()
                move_counter += 1


        print('Rolling again')
        print()


    elif random_roll == 3:
        print("Lower left Roll: ", random_roll)
        print('X is:', x)
        print('Y is:', y)

        print('moving the next element ')
        print()

        if y <= 5 and y > -1 and x > -1 and x <= 5:

            if y != 5:
                y += 1
            print('X is:', x)
            print('Y is:', y)
            new_pos = pd[y][x]
            start_position = new_pos
            print('new start_pos', start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
        elif y > 5:
            print('start pos' ,start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
            y-=1
        elif x > 5:
            print('start pos', start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
            x-=1

        else:
            x-=1
            y-=1



        # if pd[y][x] == 17 :
        #   break;

    else:
        print("Lower right Roll: ", random_roll)
        # print('Invalid Direction --  Move Count Increased:: rr: ' , random_roll)
        print('X is:', x)
        print('Y is:', y)

        print('moving the next element ')
        print()
        x += 1
        y += 1

        print('X is:', x)
        print('Y is:', y)
        print()

        if y <= 5 and y > -1 and x > -1 and x <= 5:
            new_pos = pd[y][x]
            start_position = new_pos
            # start_position = pd[y][x]
            print(' new start_pos', start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
            print('Rolling again')
            print()
        elif y > 5:
            print('start pos' ,start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
            y-=1
            print('Rolling again')
        elif x > 5:
            print('start pos', start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
            x-=1
            print('Rolling again')
            print()
        else:
            x-=1
            y-=1
            print('Rolling again')
            print()








print('outside loop')

# ---- loop end ----

# ---- Results printing ----

print('Move_counter:' ,move_counter)
avg_dots = move_counter/TOTAL_NUMBERS
print('Average number of dots', avg_dots)
for i in range(len(dots_list)):
    for j in range(len(dots_list[i])):
        print(dots_list[i][j], end=' ')
    print()

错误信息:

Traceback (most recent call last):
  File "C:/Users/.PyCharmCE2018.2/config/scratches/pyramid.py", line 199, in <module>
    new_pos = pd[y][x]
IndexError: list index out of range

Process finished with exit code 1

【问题讨论】:

  • 首先修剪所有不必要的代码(如游戏描述;谁在乎?)并粘贴完整的错误消息。
  • 如何重新粘贴?
  • 只需编辑您的问题。
  • 您的代码结构非常很糟糕。在while 循环中拥有一个巨大的if 几乎不可能进行调试。 SO上的某个人可能固执地找到了这个特定的错误,但我想说,重写你的代码。至少将所有if 分支移动到函数中。

标签: python indexoutofboundsexception


【解决方案1】:

我不确定这是否是您的错误的根源,但我确实注意到了这一行

random_roll = random.randint(upper_bound-2, upper_bound)  # Randomly selects a number from 1 to 4 to be used as fair die roll

使用upper_bound = 4,这将是random.randint(2, 4),而不是您想要的(1, 4)

不过,我也同意 DYZ 的评论,即您应该将程序拆分为函数,而不是将其全部放在包含许多 if 语句的单个循环中。

【讨论】:

  • 嗯,我在想以这种方式设置循环将确保一旦最后一个数字收到一个点,程序就会完成。我目前不明白为什么将 ifs 放入函数会有所帮助。请解释一下。
  • 主要是DRY的概念——不要重复自己。这里有很多代码可以抽象为更通用的函数,这将显着提高代码的可读性,同时帮助您修复未来的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 2011-08-16
  • 2014-02-15
  • 1970-01-01
  • 2020-08-27
  • 2015-05-18
相关资源
最近更新 更多