【问题标题】:Python Scope ConfusionPython 范围混淆
【发布时间】:2020-02-16 22:53:14
【问题描述】:

这里的想法是对矩阵进行 n 次平方,并在每次平方循环之后对其进行归一化。 我猜错误出在final_matrix-函数中,并且与范围有关。我知道这是可怕的代码,但我有点新。所以批评是非常受欢迎的:) 提前感谢!

def normalize(F):
    row_sums = F.sum(axis = 1)
    new_matrix = F / row_sums[:, np.newaxis]
    return new_matrix

#square matrix
def square(F):
    F = F.dot(F)
    return F

#calculate final matrix
def final_matrix(M, n):
    for _ in range(n):
        F = square(F) 
        N = normalize(F)
    print(N)

x = final_matrix(M,n)
print(x)

【问题讨论】:

  • 那么到底出了什么问题?
  • 没有错误数据,没有输入数据和预期的输出数据。所以这只是一个错字==>关闭请求。给出的答案可能是准确的,但对社区没有帮助。
  • 我可以给出整个代码,但正如我猜想的错误是在变量的范围内,我认为不需要更多代码的一个函数。但可能你是对的。我会对此进行审查并提供更好的信息
  • 我们不想要整个代码。但是我们确实很喜欢实际运行一个测试用例。但在这种情况下,我们可以阅读代码,并看到诸如使用F 之类的东西,其中M 会更合乎逻辑。 final_matrix里面F是怎么定义的?

标签: python numpy scope global local


【解决方案1】:

我认为你写的是“F”而不是“M”。试试这个,看看是否有效

def normalize(F):
    row_sums = F.sum(axis = 1)
    new_matrix = F / row_sums[:, np.newaxis]
    return new_matrix

#square matrix
def square(F):
    F = F.dot(F)
    return F

#calculate final matrix
def final_matrix(M, n):
    for _ in range(n):
        # Your error was here. You had written 'F' instead of 'M' in the line below
        F = square(M) 
        N = normalize(F)
    print(N)

x = final_matrix(M,n)
print(x)

【讨论】:

  • 感谢您的回答:)!我会看看我是否让它在我的代码中运行
猜你喜欢
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 2015-08-07
  • 2021-11-08
  • 2020-06-13
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多