本文介绍了Python未定义递归函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Python 3.5.0 中制作一个二叉树,并为它制作了插入函数.但是当我在内部调用 tree_insert 时遇到了一些问题,它给了我这个错误:

文件D:/MadeUpPath/BinaryTree.py",第 10 行,在 tree_insert 中

tree_insert(data, self.left)

NameError: name 'tree_insert' 未定义

class BinaryTree():def __init__(self, data):self.left = 无self.right = 无self.data = 数据def tree_insert(self, data):如果(数据< self.data):如果(self.left != None):树插入(数据,self.left)别的:self.left = 二叉树(数据)别的:如果(self.right != None):树插入(数据,self.right)别的:self.right = 二叉树(数据)

经过进一步测试,我发现递归函数根本不起作用.我尝试了以下代码以确保但给了我同样的错误:

def factorial(n):如果 n == 0:返回 1别的:返回 n * 阶乘(n - 1)

文件D:/MadeUpPath/BinaryTree.py",第 23 行,阶乘

返回 n * factorial(n - 1)

NameError: name 'factorial' 未定义

如果有人能指出我正确的方向,我将不胜感激:)

解决方案

tree_insert() 是一个 实例方法,通过self.tree_insert()调用:

class BinaryTree():def __init__(self, data):self.left = 无self.right = 无self.data = 数据def tree_insert(self, data):如果(数据< self.data):如果(self.left != None):self.tree_insert(数据,self.left)别的:self.left = 二叉树(数据)别的:如果(self.right != None):self.tree_insert(数据,self.right)别的:self.right = 二叉树(数据)

I'm making a binary tree in Python 3.5.0 and I'm making the insert function for it. But I'm running in a bit of a problem when I call tree_insert inside itself it gives me this error:

class BinaryTree():
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

    def tree_insert(self, data):
        if (data < self.data):
            if (self.left != None):
                tree_insert(data, self.left)
            else:
                self.left = BinaryTree(data)
        else:
            if (self.right != None):
                tree_insert(data, self.right)
            else:
                self.right = BinaryTree(data)

Upon testing further I found out that recursive functions simply don't work. I tried the following code to be sure but gave me the same error:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

If anyone can point me in the right direction it would be much appreciated :)

解决方案

tree_insert() is an instance method, call it via self.tree_insert():

class BinaryTree():
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

    def tree_insert(self, data):
        if (data < self.data):
            if (self.left != None):
                self.tree_insert(data, self.left)
            else:
                self.left = BinaryTree(data)
        else:
            if (self.right != None):
                self.tree_insert(data, self.right)
            else:
                self.right = BinaryTree(data)

这篇关于Python未定义递归函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:49