Python 如何将递归转换为循环以避免最大递归错误

Python 如何将递归转换为循环以避免最大递归错误,python,recursion,iteration,Python,Recursion,Iteration,以下是我的程序中的一段代码: def get_data(self): self.position = self.hfile.tell()/self.sizeof_data try: self.iq = scipy.fromfile(self.hfile, dtype=self.datatype, count=self.block_length) except MemoryError: print "End of File"

以下是我的程序中的一段代码:

def get_data(self):
    self.position = self.hfile.tell()/self.sizeof_data


    try:
        self.iq = scipy.fromfile(self.hfile, dtype=self.datatype, count=self.block_length)


    except MemoryError:
        print "End of File"
    else:
        self.iq_fft = self.dofft(self.iq)
    x = self.iq_fft

        maximum = np.argmax(x)
        average = np.mean(x)

    print "\nAvage Value: ", average 

        #set up Get Data loop
        loops = self.files/self.block_length
        self.counter += 1
        count = self.counter
        count += 1
        print "\nCOUNT: ", count
        #print "\nloop: ", loops

    if count == loop:
        raise SystemExit #Exits program gracefully
    else:   
        self.get_data()



def dofft(self, iq):
    N = len(iq)

    iq_fft = scipy.fftpack.fftshift(scipy.fft(iq))       # fft and shift axis


    iq_fft = scipy.log10(abs((iq_fft))) # convert to decibels, adjust power
    # adding 1e-15 (-300 dB) to protect against value errors if an item in iq_fft is 0

    return iq_fft

它工作得很好,除非循环大于989,否则整个过程都会崩溃。我已经看到一些关于Python中递归如何限制为999的讨论,所以我知道这是问题所在,但是如何重写循环以避免错误?循环可能会变得相当大,因此我认为使用setrecursionlimit()函数不是一个好主意。

可能是这样的:

while count != loop
    #run whatever is in get data
else
    raise SystemExit

但是,如果您提供了更多信息,我可能会选择
for
循环。

让您的函数返回绑定函数,然后运行它,直到没有函数返回为止。 可以在functools中使用分部绑定函数

from functools import partial
def yourfunc(test):
    # code
    if answer:
        return answer
    return partial(yourfunc,boundvariable)

要确切地说出你想要完成什么有点困难,但看起来你需要这样的东西

import scipy as sp
import scipy.fftpack as sf

def db_fft(block):
    res = sp.fft(block)         # compute FFT
    res = sf.fftshift(res)      # shift axis
    res = sp.log10(abs((res)))  # convert to db, adjust power
    return res

class BlockFFT:
    def __init__(self, fname, dtype=sp.float64, blocksize=256*256):
        self.hfile     = open(fname, "rb")
        self.dtype     = dtype      # data type
        self.blocksize = blocksize  # number of items per step

    def next(self):
        try:
            block = scipy.fromfile(self.hfile, dtype=self.dtype, count=self.blocksize)
            fft   = db_fft(block)
            return fft, sp.argmax(fft), sp.mean(fft)
        except MemoryError:
            self.hfile.close()
            raise StopIteration()

def main():
    for fft, max_, avg_ in BlockFFT("myfile.dat"):
        # now do something with it
        pass

if __name__=="__main__":
    main()

我不明白为什么你把它写成递归,而这显然是一个迭代过程(我理解为逐块读取文件)


在没有看到递归版本的情况下,很难回答这个问题!您将迭代什么,每次迭代都做什么,以及您是如何决定完成的?“我看到一些关于Python中递归如何限制为999的讨论,所以我知道这就是问题所在”-这就是所谓的假设,这是我和我遇到的大多数工程师编写错误的主要原因之一。将来,即使某件事很有可能发生,也要确定它是原因。我不明白你为什么要反复地称它为;每次你叫它,它都会踩在self.position,self.iq,self.iq\u fft,self.counter上。。。我认为您需要创建一个self.next()方法,该方法为每个块返回这些值,并在到达文件末尾时引发StopIteration,然后您可以遍历类上的块。
def get_data(self):
    for count in range(self.files/self.block_length):
        self.position = self.hfile.tell()/self.sizeof_data

        try:
            self.iq = scipy.fromfile(self.hfile, dtype=self.datatype, count=self.block_length)
        except MemoryError:
            print "End of File"

        self.iq_fft = self.dofft(self.iq)
        x = self.iq_fft

        maximum = np.argmax(x)
        average = np.mean(x)

        print "\nAverage Value: ", average 

        self.counter += 1
        print "\nCOUNT: ", count
    raise SystemExit