【问题标题】:Returning string creates Tuple Python recursion返回字符串创建元组 Python 递归
【发布时间】:2018-04-10 13:48:00
【问题描述】:

我在 Python 中有一个递归方法。不确定它是否有帮助,但它会检查 AVL 树的不平衡程度。例如,10,20,30 是“rr”,30,20,10 是“ll”,10,20,15 是“rl”,20,10,15 是“lr”。
这是我的代码:

def rotation_type(bst, ptr='dummy'):
    if ptr == 'dummy':
        ptr = bst.root
    if ptr.left != None or ptr.right != None:
        if ptr.left != None:
            return 'l', rotation_type(bst,ptr.left)
        else:
            return 'r', rotation_type(bst,ptr.right)

我的代码有效,但它返回一个元组。例如,如果我的二叉树是 [10,20,30],它会返回 ('r', ('r', None))。有没有办法只返回像'rr'这样的字符串?抱歉,如果以前有人问过这个问题,但我在任何地方都找不到。在此先感谢

【问题讨论】:

  • 对于两个孩子都存在的节点应该返回什么?然后节点平衡,但您可能希望在两个孩子中继续递归?
  • 如果两者都存在,我已经得到了函数,如果没有,我正在调用这个函数

标签: python python-3.x recursion tuples


【解决方案1】:

需要把递归结果串联起来,所以每次都返回一个字符串:

return 'l' + rotation_type(bst, ptr.left)

补充说明:

  • 使用<something> is None<something> is not None 测试None 值; None 是单例。

  • 我会使用 None 作为默认值,而不是签名中的字符串。

  • None 是一个虚假值,您可以只使用if ptr.leftif ptr.right

  • 您需要为两个孩子都失踪的情况返回一些东西。

改进版:

def rotation_type(bst, ptr=None):
    ptr = ptr or bst.root
    if ptr.left:
        return 'l' + rotation_type(bst, ptr.left)
    elif ptr.right:
        return 'r' + rotation_type(bst, ptr.right)
    else:
        return ''

【讨论】:

  • 函数端也要有return '',避免Nonestr concat错误
  • 谢谢,不敢相信我没有想到这一点。
【解决方案2】:

是的,一个简单的解决方法是在元组,上使用字符串连接+

def rotation_type(bst, ptr='dummy'):
    if ptr == 'dummy':
        ptr = bst.root
    if ptr.left != None or ptr.right != None:
        if ptr.left != None:
            return 'l' + rotation_type(bst,ptr.left)
        else:
            return 'r' + rotation_type(bst,ptr.right)
    return ''

如果没有返回任何内容(最后一行),您还必须返回空字符串,否则我们会将字符串与None-type 连接起来,这会出错。

我还建议使用 None 而不是 dummy,因为这通常是占位符,但确实有充分的理由不这样做:

def rotation_type(bst, ptr=None):
    if ptr is None:
        ptr = bst.root
    if ptr.left != None or ptr.right != None:
        if ptr.left != None:
            return 'l' + rotation_type(bst,ptr.left)
        else:
            return 'r' + rotation_type(bst,ptr.right)
    return ''

您仍然可以改进代码,但我将其留作练习。

【讨论】:

  • 谢谢,不敢相信我没想到这一点。我会接受 Ghostly 的解决方案,因为他是第一个。
猜你喜欢
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-02
  • 2022-01-06
相关资源
最近更新 更多