【问题标题】:How to stop algorithm if "statement if" is true?如果“statement if”为真,如何停止算法?
【发布时间】:2021-10-09 13:24:14
【问题描述】:

我有这样的 if/else 语句:

import numpy as np
rows_b = int(input("Enter the number of rows of matrix B : " ))
column_b = int(input("Enter the number of columns of matrix B : "))

print("Input elements of matrix B1:")
B1= [[float(input()) for i in range(column_b)] for j in range(rows_b)]
   
print("Input elements of matrix B2:")
B2= [[float(input()) for i in range(column_b)] for j in range(rows_b)]

b1 = np.array(B1)
b2 = np.array(B2)

result = np.all(b1 == b2[0])
if result:
    print('matrix B1 = B2')
    #if matrix B1 = B2, go to the next algorithm

else:
    print('matrix B1 and B2 are not equivalent') 
    #if B1 and B2 are not equivalent, stop here.

B = np.array(B1)
print("Matrix B is: ") 
for x in B:
    print(x)

我想如果 B1 = B2 然后继续下一步(B = np.array (B1))但是(否则)如果 B1 和 B2 不相等则停止算法(不继续 B = np.array (B1 )),怎么样?

【问题讨论】:

  • 要么将 B = np.array(B1) 的其余代码保留在 if 条件内,要么使用 exit()in else 部分。
  • 强制警告:你不能compare floating point值!您需要将其与 epsilon 或 isclose in numpy 进行比较。
  • @ThePyGuy 不,exit 不是要走的路。引用documentation of exit and quit:“它们对交互式解释器外壳很有用,不应该在程序中使用。”
  • @Matthias,这也是Trueexit 不是推荐的方式

标签: python matrix conditional-statements


【解决方案1】:

放入if

if B1 == B2:
  B = np.array(B1)
  print("Matrix B is: ") 
  for x in B:
    print(x)

else:
    print('matrix B1 and B2 are not equivalent') 
    #if B1 and B2 are not equivalent, stop here.

【讨论】:

  • 我建议在这里添加相同的警告。 B1 == B2 将比较所有元素和浮点值can't accurately be compared with equality
  • 那么我应该怎么做才能与浮点值进行比较?
  • 如何在 if/else 语句中使用 np.isclose()?
  • @MiraWadu 如果您只想检查一个数组中的所有元素是否等于另一个数组中的所有元素,您可以使用if np.allclose(B1, B2)。阅读它here
猜你喜欢
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 2012-05-13
  • 1970-01-01
相关资源
最近更新 更多