【问题标题】:Why isn't Pythons randint Function actually Random?为什么 Python 的 randint 函数实际上不是随机的?
【发布时间】:2015-05-29 02:06:23
【问题描述】:

我已经用 python 编码了一段时间,我偶然发现了 Codecademys 的练习,其中一个项目是创建一个战舰游戏,该游戏将 2x1 战舰随机放置在 5x5 网格中。在我的女朋友连续 3 次正确猜出船在哪里后,我注意到了一个模式。 col 的 randint 和行的 randint 从 0,1 开始。然后程序终止。再次启动程序后,答案是 1,2。接下来的三个答案是 2,3 , 3,4 , 4,0。为什么会发生这种情况而不是真正随机?

代码如下:

import os, sys
from random import randint
os.system("cls")
board = []
for x in range(0, 5):
    board.append(["O"] * 5)
def print_board(board):
    for row in board:
        print " ".join(row)
print_board(board)
def random_row(board):
    return randint(0, len(board) - 1)
def random_col(board):
    return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
# Write your code below!
while guess_row!=ship_row and guess_col!=ship_col:
    print"You missed my battleship!"
    for i in range(len(board)):
        if i==guess_col:
            board[guess_row][i]="X"
    print_board(board)
    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))
print"Congratulations! You sank my Battleship!"

【问题讨论】:

  • 如果您认为在库中发现了与随机一样重要的重大缺陷,那么问题可能就在您身上。

标签: python random numbers


【解决方案1】:

您的情况存在错误 - 您应该检查行或列是否错误,而不是两者是否都错误。事实上,如果只有一个数字是错误的,你的程序就会说你赢了——所以有很多输入是赢的。您注意到的模式只是一个巧合。

【讨论】:

    猜你喜欢
    • 2019-11-23
    • 2010-12-31
    • 2015-11-06
    • 2015-08-18
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2022-09-22
    相关资源
    最近更新 更多