[英]Error in code, for program that asks input of index for 2d array and outputs the value at that index
[英]How can i create a program that asks for input of index of 2d array and outputs the value at that index?
編寫一個程序,允許用戶輸入 integer 值並查詢大小為 9x9 的二維數組。 然后,您的程序應向用戶詢問由空格分隔的一對坐標 (x,y),並返回由給定坐標指定的 position 處的值。 例如,0 3 應該返回值 7(第一行第四列的值——記住數組索引從零開始)。 假設每個 integer 都是從 1 到 9 的單個數字。輸入 -1 作為任一坐標以結束程序。
Sample I/O:
Enter an array:
359716482
867345912
413928675
398574126
546281739
172639548
984163257
621857394
735492861
Enter coordinates: 0 3
Value = 7
Enter coordinates: 5 5
Value = 9
Enter coordinates: 8 8
Value = 1
Enter coordinates: -1 -1
DONE
到目前為止,這是我的代碼:
arr = input("Enter an array:\n")
coordinates = input("Enter coordinates:\n")
x = coordinates[:1]
y = coordinates[2:3]
while x!= -1 or x!= -1 :
x = coordinates[:1]
y = coordinates[2:3]
x = int(x),
y = int(y)
value = arr[x][y]
print("Value = "+ arr)
這是非常粗糙的。 我了解我需要做什么,並且我知道如何去做,但是我正在努力進行實際編程。 我的想法是創建一個哨兵循環,一旦用戶輸入 -1 作為坐標就退出。 使用 while 循環,我們要求坐標,然后剪切字符串以獲取單獨的 x 和 y 坐標,然后使用它來查找指定索引中的數字。
我已經用說明的步驟注釋了下面的代碼。
print("Enter an array")
# read 9 lines into the list
arr = [input() for _ in range(9)]
while True:
# Read a line of coordinates, split into two elements, convert to integers
x, y = map(int, input("Enter coordinates: ").split(' ', 2))
# Stop if sentinel in either coordinate
if -1 in (x, y):
print("DONE")
break
# print the element at the specified coordinates
print(f"Value = {arr[x][y]}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.