【问题标题】:python3 why root_a return None value in my code?python3 为什么 root_a 在我的代码中返回 None 值?
【发布时间】:2022-09-30 21:51:06
【问题描述】:

我的代码是这样的,输入在这里。

5 6

1 2

1 5

2 4

3 4

3 5

4 5

当我输入 2 4 时,值 root_a 为无。但我不明白为什么 root_a 返回 None 。我试图在 pycharm 上调试,但我不知道为什么...... 有人可以帮忙吗?

node, edge = list(map(int, input().split()))
root_list = [x for x in range(node)]


def find_root(x):
    print(x, \'x\')
    if x == root_list[x]:
        return x
    root_x = find_root(root_list[x])
    root_list[x] = root_x


for _ in range(edge):
    a, b = list(map(int, input().split()))
    a = a - 1
    b = b - 1
    root_a = find_root(a)
    root_b = find_root(b)
    print(root_a, root_b, \'root\')
    if root_a != root_b:
        root_list[b] = root_a
    print(root_list)

    标签: python python-3.x


    【解决方案1】:

    如果我错误地理解了您的代码,我深表歉意。我不太确定你想要达到什么目标;(

    但是我可以告诉你为什么当你输入2 4时它是None

    那是因为在函数 find_root 中,如果 x != root_list[x] 没有返回任何内容

    请参阅下面的 find_root 函数与 cmets

    def find_root(x):
        print(x, 'x')
        if x == root_list[x]:
            return x
        # here if x != root_list[x], the code will continue
        # but there is no return, hence it's treated as if it returns None
        root_x = find_root(root_list[x])
        root_list[x] = root_x
        # you might need a return here?
        return root_x
    

    【讨论】:

      猜你喜欢
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 2023-02-12
      • 2020-02-07
      • 1970-01-01
      • 2017-07-16
      • 2019-03-03
      • 2013-07-13
      相关资源
      最近更新 更多