我是一名Python初学者,我被困在这里。我编写了以下程序,生成随机数矩阵。
def randsq(size):
for i in range(size):
for j in range(size):
print(random.randint(0,9), end = '')
print()
无论如何我可以添加一个从输入参数中获取单词并在矩阵中对角隐藏它的函数吗?因此,如果用户输入'rain',则输出如下所示:
r123
1a45
23i4
989n
谢谢!
答案 0 :(得分:1)
修改后的代码:
import random
def randsq(word):
size = len(word)
for i in range(size):
for j in range(size):
if i == j: # we are at a diagonal-value
print(word[i], end='') # it's the i-th diag -> choose i-th char
else:
print(random.randint(0, 9), end='')
print()
randsq('Rain')
输出:
R757
0a91
02i9
757n
如果您希望用户输入以下单词:
word_to_hide = input('Which word to hide? (+enter) ') # will wait for user-input + enter
randsq(word_to_hide)