确保一个动作在递归过程中只发生一次

2024-06-25 23:13:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个过程,其中包含一个步骤,它涉及递归调用过程。我希望某个操作不是第一次执行,而是在其他时间执行它被递归调用。在

def a(string):
    while string.startswith('/'):
        string =string[1:]
    stringa = string.split('/',1)

    if(len(stringa)>1):
        a(stringa)

基本上我的字符串是/a/b/c/d类型。我希望第一次使用stringa作为{/}{a/b/c/d},并在后续递归中
stringa={a}{b/c/d}
stringa={b}{c/d}
stringa={c}{d}


Tags: 字符串类型stringlenif过程def时间
1条回答
网友
1楼 · 发布于 2024-06-25 23:13:23

基本模式是使用标志。可以将标志设置为默认参数,这样在第一次调用函数时不必传递它,然后函数在递归调用时设置(或取消设置…)标志。在

看起来像这样:

def some_function(..., is_first=True):
    if is_first:
        # code to run the first time
    else
        # code to run the other times
    # recurse
    some_function(..., is_first=False)

我不知道如何把它转换成你的代码,因为不清楚你第一次想做什么。另外,您首先传入一个字符串,但是递归调用传递的是一个列表。在

相关问题 更多 >