Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python3.x问题中向文件写入遍历_Python_Python 3.x_File Io_Heap_Traversal - Fatal编程技术网

在python3.x问题中向文件写入遍历

在python3.x问题中向文件写入遍历,python,python-3.x,file-io,heap,traversal,Python,Python 3.x,File Io,Heap,Traversal,我试图遍历一个堆,并将遍历写入一个文件,但我失败得很惨 当我只想在文件中打印出节点时,我的终端会收到一个最大遍历深度的问题。我认为您的代码应该更像这样: def inorder(self, file): if self._left is not None: file.write(str(self) + ' ') self._left.inorder(file) file.write(str(self) + ' ') if self.

我试图遍历一个堆,并将遍历写入一个文件,但我失败得很惨


当我只想在文件中打印出节点时,我的终端会收到一个最大遍历深度的问题。

我认为您的代码应该更像这样:

def inorder(self, file):    
    if self._left is not None:
        file.write(str(self) + ' ')
        self._left.inorder(file)
    file.write(str(self) + ' ')
    if self._right is not None:
        file.write(str(self) + ' ')
        self._right.inorder(file)
请注意:

  • 要写入的
    文件是一个参数,传递给递归调用,而不是每次打开
    ed
    
  • 通过身份不平等测试
    None
    ;及
  • 我假设您有一个树结构,其中
    self.\u left
    self.\u right
    是与
    self
    相同的类的实例(由于您提供的类太少,很难确定,
    self.inoder(self.\u left)
    没有意义) 在类的某个实例
    instance
    上调用此函数时,它将如下所示:

    with open(...) as f:
        instance.inorder(f)
    

    为什么不将文件
    j
    作为一个参数,而不是将其保持打开状态?另外,您的检查应该是
    不是None
    @jornsharpe编辑了我的代码-它们应该是不同的文件,每个遍历一个,这不是我的意思;每次递归都要重新打开,只需在外部打开一次,然后将文件对象作为参数传入。很抱歉,恐怕我不明白。我应该将with open放在函数定义的上方?例如,
    def inorder(self,I):
    然后用open(…)将其称为I:instance.inorder(I)