有没有办法制作没有重复值的矩阵?
import random
def main():
values = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
for r in range(5):
for c in range(5):
rand = random.randint(1, 25)
if values[r][c] != rand:
values[r][c] = rand
for i in range(5):
print("\n")
for j in range(5):
print("\t" + str(values[i][j]), end=" ")
main()
此代码应该打印一个 5 x 5 矩阵,范围为 1-25,且不重复数字。由于某种原因,我输入的 if 命令没有随机化它。有人可以帮我解决问题吗?
import random
def main():
values = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
for r in range(5):
for c in range(5):
rand = random.randint(1, 25)
if values[r][c] != rand:
values[r][c] = rand
for i in range(5):
print("\n")
for j in range(5):
print("\t" + str(values[i][j]), end=" ")
main()
This code should've printed a 5 x 5 matrix with a range of 1-25 without repeating the number. For some reason, the if command I did put in did not randomize it. Can someone help me with the solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
首先创建一个从 1 到 25 的数字列表。然后随机洗牌。最后你用它创建一个矩阵。
Try this:
First you create a list of numbers from 1 to 25. Then you randomly shuffle it. And finally you create a matrix out of it.
原始代码显示了尝试确保某个值仅使用一次。
但是,代码会检查
values[r][c]
处的特定值,即0
的初始值。因此,rand
被分配给该位置。这不会阻止生成相同的rand
值并稍后将其分配给另一个位置(即重复的位置)。测试结果:
The original code shows an attempt to make sure a value is used only once.
However, the code checks a specific value at
values[r][c]
which is the initial value of0
. So,rand
is assigned to that location. This does not prevent the samerand
value from being generated and assigned later to another location (i.e., a duplicate).Test results: