【问题标题】:How do I change the maximum and minimum element in the matrix row? [closed]如何更改矩阵行中的最大和最小元素? [关闭]
【发布时间】:2021-03-29 14:58:48
【问题描述】:

如何更改矩阵行中的最大和最小元素?

下面我给出了我的代码,它不能正常工作,行中的最大和最小元素被错误地交换,程序不稳定。

number_of_rows = int(input("Enter the number of rows: ")) #matrix generator
m = [[int(j) for j in input("Enter all the elements of a single row (separated by a space): ").split()] for i in range(number_of_rows)]
print("Your matrix : ", *m, sep = '\n')

    for i, row in enumerate(m):
        max = min = 0
        for j, elem in enumerate(row):
            if elem > row[max]:
                max = j
            if elem < row[min]:
                min = j
        row[max], row[0] = row[0], row[max]
        row[min], row[-1] = row[-1], row[min]
    print(m)

【问题讨论】:

  • 请创建一个minimal reproducible example
  • maxmin 在 Python 中已经有了意义。最好不要通过声明同名变量来隐藏这些函数。
  • 我应该删除变量的最大和最小替换行吗?

标签: python arrays python-3.x matrix


【解决方案1】:

我同意来自@Pranav Hosangadi 的 cmets 关于您对变量使用 min 和 max 的看法。以下是我将如何执行矩阵交换功能​​:

for r, row in enumerate(m):
    mx_val = -float('inf')  #Sets max value to extremely low value to start
    mn_val = float('inf')   #Sets min_val to very high value to start
    mx_ptr = 0              # used to keep track of where in row max occurs
    mn_ptr = 0              #used to keep track of where min occurs
    for c, col in enumerate(row):           
        if col > mx_val:    #Test for col greater than current mx_val
            mx_ptr = c      # save the pointer
            mx_val = col    #save the value
        if col < mn_val:
            mn_ptr = c
            mn_val = col
    row[mn_ptr] = mx_val    #set row cell with mn_val to mx_val
    row[mx_ptr] = mn_val    #set row cell with mx_val to mn_val
print(m)    

【讨论】:

  • 谢谢你,@itprorh66
猜你喜欢
  • 2014-04-08
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
相关资源
最近更新 更多