TQC+ 程式語言Python 608 最大最小值索引
題目說明:
請撰寫一程式,讓使用者建立一個3*3的矩陣,其內容為從鍵盤輸入的整數(不重複),接著輸出矩陣最大值與最小值的索引。
範例輸入
6
4
8
39
12
3
-3
49
33
範例輸出
Index of the largest number 49 is: (2, 1)
Index of the smallest number -3 is: (2, 0)
程式碼:
matrix = []
for i in range(3):
matrix.append([])
for j in range(3):
matrix[i].append(eval(input()))
largestList = [max(matrix[0]), max(matrix[1]), max(matrix[2])]
smallestList = [min(matrix[0]), min(matrix[1]), min(matrix[2])]
largest = max(largestList)
smallest = min(smallestList)
largestIndex1 = largestList.index(largest)
smallestIndex1 = smallestList.index(smallest)
largestIndex2 = matrix[largestIndex1].index(largest)
smallestIndex2 = matrix[smallestIndex1].index(smallest)
print('Index of the largest number %d is: (%d, %d)' %(largest, largestIndex1, largestIndex2))
print('Index of the smallest number %d is: (%d, %d)' %(smallest, smallestIndex1, smallestIndex2))
或是
matrix = []
for i in range(9):
matrix.append(eval(input()))
largest = max(matrix)
largestIndex1 = matrix.index(largest) // 3
largestIndex2 = matrix.index(largest) % 3
smallest = min(matrix)
smallestIndex1 = matrix.index(smallest) // 3
smallestIndex2 = matrix.index(smallest) % 3
print('Index of the largest number %d is: (%d, %d)' %(largest, largestIndex1, largestIndex2))
print('Index of the smallest number %d is: (%d, %d)' %(smallest, smallestIndex1, smallestIndex2))