为什么python返回时超出界限?

时间:2019-12-06 00:18:16

标签: python python-3.x

似乎在第一个循环中可以正常工作,但在第二个循环中却不能。这是为什么?我认为它应该可以正常工作。

import numpy as np

rows = 20
seatsInRow = 1000000
randRow = lambda: np.random.randint(1, rows)
randSeat = lambda: np.random.randint(1, seatsInRow)
cinema = [[1 for x in range(seatsInRow)] for y in range(rows)]

for i in range(1, rows):
    for j in range(1, seatsInRow):
        cinema[i][j] = 1

def checkIfDoubleSeatsLeft():
    for i in range(1, rows):
        for j in range(1, seatsInRow-1):
            if (cinema[i][j]==1 and cinema[i][j+1]==1):
                return True
    return False

def countSeatsLeft():
    count = 0
    for i in range(1, rows):
        for j in range(1, seatsInRow):
            if (cinema[i][j]==1):
                ++count
    return count

selectedRow = 0
selectedSeat = 0
seatsAvailability = True
while (seatsAvailability):
    selectedRow = randRow()
    selectedSeat = randSeat()
    if (selectedSeat < seatsInRow):
        if (cinema[selectedRow][selectedSeat]==1 and cinema[selectedRow][selectedSeat+1]==1):
            cinema[selectedRow][selectedSeat] = 0
            cinema[selectedRow][selectedSeat+1] = 0
    seatsAvailability = checkIfDoubleSeatsLeft()

remainedSeats = countSeatsLeft()
print("Percentage that's left is " + remainedSeats/20000000)

使用完整代码更新了帖子。需要更多详细信息,在这里)

1 个答案:

答案 0 :(得分:1)

selectedSeat 最多可以等于 seatsInRow ,这也是矩阵的Y维。因此,您无法在高于 seatsInRow-1 的索引处访问矩阵。但是,您可以在这两行中做到这一点:

if (cinema[selectedRow][selectedSeat]==1 and cinema[selectedRow][selectedSeat+1]==1):
cinema[selectedRow][selectedSeat+1] = 0

因此,您必须确保 randSeat()返回的值最多等于 seatsInRow-1

randSeat = lambda: np.random.randint(1, seatsInRow - 1)

此外,您不能只将浮点数与字符串合并,这需要正确的格式:

print("Percentage that's left is {}".format(remainedSeats/20000000))