【问题标题】:How to change recursive function如何更改递归函数
【发布时间】:2021-10-10 10:14:05
【问题描述】:

如何更改函数以使其不再是递归的?我认为内存缓冲区正在被填充。

代码:

def start_play():
    start = driver.find_element_by_xpath('/html/body/div[27]/div[2]/div[3]/div[1]/div[1]/span')
    start = start.text
    start = re.findall(r'\d+', start)

    if len(start) == 0:
        # t.sleep(2)
        return start_play()
    else:
        if start[0] == '3' or start[0] == '4':
            comparison()
        else:
            return start_play()
        
def check_win_or_lose():
    start = driver.find_element_by_xpath('/html/body/div[27]/div[2]/div[3]/div[1]/div[1]/span')
    start = start.text
    start = re.findall(r'\d+', start)

    if len(start) == 0:
        return check_win_or_lose()
    else:
        if start[0] == '22' or start[0] == '23':
            check()
            last_bet.clear()
        else:
            return check_win_or_lose()

【问题讨论】:

  • 您的代码中没有退出条件。它一直运行直到达到最大深度。

标签: python python-3.x selenium recursion


【解决方案1】:

有你的两个函数以迭代方式:

def start_play():
    while True:
        span = driver.find_element_by_xpath('/html/body/div[27]/div[2]/div[3]/div[1]/div[1]/span')
        start = re.findall(r'\d+', span.text)
        if start and start[0] in ('3', '4'):
            comparaison()
            break


def check_win_or_lose():
    while True:
        span = driver.find_element_by_xpath('/html/body/div[27]/div[2]/div[3]/div[1]/div[1]/span')
        start = re.findall(r'\d+', span.text)
        if start and start[0] in ('22', '23'):
            check()
            last_bet.clear()
            break

【讨论】:

  • if len(start) != 0 可以简化为 if start
  • 其实可以进一步简化为start[0] in ('3', '4'),第二种情况类似。
【解决方案2】:

一点都不难。只是没有函数调用本身。如果您希望它永远循环,请明确说明。

def wrong():
   # do things here
   return wrong()

def right():
    while True:
        # do things here

如果您想在# do things here 的某个位置退出while True:,您可以使用break 执行此操作。

def wrong_too():
   # do things here
   if something:
       # do nothing, or something else
   else:
       return wrong_too()

def right_too():
    while True:
        # do things here
        if something:
            break

在更复杂的情况下,可能会使用状态变量。

def right_also():
    done = False
    while not done:
        # do things here
        while complex_stuff():
            for loop in values():
                if something_particular():
                    # We want to escape down at the end of the while True
                    done = True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2014-02-16
    相关资源
    最近更新 更多