在python中继续递归函数

时间:2021-05-20 18:13:19

标签: python python-3.x function loops recursion

我想知道如何编写一个重复而不收到错误消息的函数:

<块引用>

递归错误:实例检查中超出了最大递归深度_

重复递归函数是main():

import tkinter as tkin
import math
import hmac
import hashlib
import sys

n = 0
sys.setrecursionlimit(2450)
root= tkin.Tk()
canvas1 = tkin.Canvas(root, width = 300, height = 300)
canvas1.pack()
label1 = tkin.Label(root, text= 'Number', fg='green', font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 200, window=label1)

def dice ( serverSeed, clientSeed, nonce ):
    round = 0
    nonceSeed = '{}:{}:{}'.format(clientSeed, nonce, round)
    hex = hmac.new(bytes(serverSeed, 'utf-8'), bytes(nonceSeed, 'utf-8'), hashlib.sha256).hexdigest()[0:8]
    i = 0
    end = 0
    while i < 4:
        end += int(hex[i*2:i*2+2], 16) / math.pow(256, i+1)
        i+=1
    end = math.floor(end * 10001) / 100
    return str(end)
    
def main ():
    global n
    n += 1
    roll = float(dice('535e8f53eee1402b242c7eff4038787d3de850c3ba27bde6a370225e1a2f23dd', '8cf82c02b3', n))
if n % 2400 == 0:
        label1.configure(text=roll)
        label1.update();
    main()
   
button1 = tkin.Button(text='Click Me',command=main, bg='brown',fg='white')
canvas1.create_window(150, 150, window=button1)

root.mainloop()

编辑: 添加了递归限制和 root.after(int, function)

limit = 2400
def main ():
    global n
    global max
    n += 1
    roll = float(dice('535e8f53eee1402b242c7eff4038787d3de850c3ba27bde6a370225e1a2f23dd', '8cf82c02b3', n))
    if n % limit == 0:
        label1.configure(text=roll)
        label1.update();
        limit+=2400
        root.after(0, main)
    else:
        main()

2 个答案:

答案 0 :(得分:0)

你为什么不写这样的东西

def main ():
    n = 0
    while True:
        n += 1
        roll = dice('535e8f53eee1402b242c7eff4038787d3de850c3ba27bde6a370225e1a2f23dd', '8cf82c02b3', n)
        if n % 2440 == 0:
            label1.configure(text=roll)
            label1.update();

编辑 - 我看到有人在我输入答案时提出了这个建议

答案 1 :(得分:0)

为什么要超过最大递归?这不是递归的用途。
虽然这不会回答你的问题,因为我认为增加递归深度没有意义,我将尝试解释一些事情。

递归不能代替循环。是的,它可以代替循环,但工作方式不同。

每次调用函数时,函数中的数据都会保存在您的内存中,直到该函数返回或以不同方式释放该内存(未捕获的异常、del 或覆盖)。

想象一个理论上的函数,将 500MB 加载到内存中,如果您在其内部调用它,您的内存中将有 1GB。再次调用它,您将拥有 1.5GB。
想象一下,如果您决定进行无限递归会发生什么。如果此递归达到返回条件,则所有内存都将被释放,否则它将继续堆叠直到内存耗尽。

使用循环,它们更适合您的需要。