def largestlowest(matrix):
largeset = 0
lowest = 0
for row in range(len(matrix)):
for col in range(len(matrix[row]-1)):
if matrix[col] > matrix[col+1]:
largest = matrix[col]
if matrix[col] < matrix[col+1]:
lowest = matrix[col]
else:
print("there is no min/max value")
return largest and lowest
print(largestlowest([[4,8,2,9,34,57,22,44], [1,2,8,9,1,2,55,3,22,4]]))
答案 0 :(得分:1)
别忘了提及语言。我认为这是python。在发布代码之前,还尝试运行和测试代码。这段代码根本没有运行。
这是您在python中提交的代码的运行版本:
def largestlowest(matrix):
largeset = 0
lowest = 0
for row in range(len(matrix)):
for col in range(len(matrix[row])-1):
if (matrix[row][col] > matrix[row][col+1]):
largest = matrix[row][col]
if (matrix[row][col] < matrix[row][col+1]):
lowest = matrix[row][col]
return (largest, lowest)
print(largestlowest([[4,8,2,9,34,57,22,44], [1,2,8,9,1,2,55,3,22,4]]))
请注意,要访问列表的元素,应同时使用
row
和column
:matrix[row][col]
来调用它。
有些错误:
(len(matrix[row])-1)
,因此不包括
最后一列。 matrix[row][col] > matrix[row][col+1]
,而不是将所有元素与最低和最大元素进行比较。return a and b
仅返回a
我建议您搜索每个步骤(例如如何在python中调用矩阵元素)。您会在网上找到大量信息。尝试尽快运行代码并解决控制台中的错误。 最后,执行您想要的代码(我认为):
def largestlowest(matrix):
if (not len(matrix)):
return ("Matrix should have at least one element!")
## assign largest and lowest to first element of martix
largest = lowest = matrix[0][0]
for row in range(len(matrix)):
for col in range(len(matrix[row])):
if (matrix[row][col] > largest):
largest = matrix[row][col]
if (matrix[row][col] < lowest):
lowest = matrix[row][col]
# return (largest, lowest)
return "Largest element of matrix: %d, lowest element of matrix: %d" % (largest, lowest)
print(largestlowest([[4,8,2,9,34,57,22,44], [1,2,8,9,1,2,55,3,22,4]]))
print(largestlowest([]))
答案 1 :(得分:0)
您的代码实际上是在比较错误的值:
if matrix[col] > matrix[col+1]:
并未将当前值与最大值进行比较,而是将其与之后的值进行了比较。小孩子也发生了同样的事情。
此外,您还不正确地处理了数据。 matrix[col]
本身就是数组,而不是单个元素(至少根据您给出的示例)。
下面的代码已注释并可以使用。它输出:
LARGEST: 57
LOWEST: 1
# Function
def largestlowest(matrix):
# Declaring biggest and smallest variable. Setting extraneous at first
largest = -10000
lowest = 10000
# Loop through every array in the matrix as you have defined it
for arr in matrix:
# Loop through each item in the array
for item in arr:
# If it is bigger than the largest, set the largest to be that value
if item > largest:
largest = item
# If it is smaller than the smallest, set the smallest to be that value
if item < lowest:
lowest = item
# Return the largest and lowest
return largest, lowest
# Example main function
def main():
# Define a test matrix (copied from your example)
matrix = [[4,8,2,9,34,57,22,44], [1,2,8,9,1,2,55,3,22,4]]
# Run the function we created
largest, lowest = largestlowest(matrix)
# Print out the results
print("LARGEST: ", largest)
print("LOWEST: ", lowest)
# Call the main function
main()