我的问题与 Tony Gaddis 的书“Starting Out With Python”(第 3 版)有关。是第7章第11题,我把题目摘下来引用一下,然后在下面解释一下我的问题。
The Lo Shu Magic Square is a grid with 3 rows and 3 columns. The Lo Shu Magic Square has the following properties: • The grid contains the numbers 1 through 9 exactly. • The sum of each row, each column, and each diagonal all add up to the same number.
In a program you can simulate a magic square using a two-dimensional list. Write a function that accepts a two-dimensional list as an argument and determines whether the list is a Lo Shu Magic Square. Test the function in a program.
我的问题:基本上,我要求用户使用数字 1-9 填充此 3x3 网格。但是,每个数字应该彼此不同。如何强制用户在给定范围(1-9)内每次输入不同的数字?有没有特殊的功能?完成我的“列表”一章后,我无法在 Python 中执行此操作。
如果有帮助,我也会提供我的代码来解决这个问题。截至目前,用户可以输入任何数字,甚至是两位数等。在此先感谢您。
# lo shu magic square
ROWS=3
COLS=3
def main():
# create the two dimensional list
square = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
for r in range(ROWS):
for c in range(COLS):
square[r][c]=int(input("Enter a number 1-9 (can't enter the same number again): "))
请您参考如下方法:
您可以创建新列表并将每个用户输入添加到该列表中。然后,你可以检查他是否已经输入了。示例:
inputs = []
while True:
inp = input("Enter something: ")
if inp in inputs:
print("Please, enter something else! You already entered that!")
else:
print("Successfully entered!")
inputs.append(inp)
您可以在您的案例中使用的示例:
numbers = []
while True:
inp = int(input("Enter number from 1 to 9: "))
if 1 <= inp <= 9 and inp not in numbers:
print("Success!")
numbers.append(inp)
else:
print("Your number is already entered or isn't in range 1-9. Please enter again.")
编辑:您已经将用户输入存储在列表中。您可以只检查列表中是否有新输入。
