簡體   English   中英

如何在python中的一段時間后退出遞歸DFS算法?

[英]How do I exit a recursive DFS algorithm after a certain time in python?

我在python中有一個遞歸深度優先搜索功能,我希望在一定時間后完全退出(整個堆棧)。 遞歸函數知道剩余的時間(它傳遞了一個名為time_remaining的變量),當這個time_remaining小於100毫秒時,我想退出整個遞歸堆棧,並返回一些默認值。 在python中實現這一目標的最佳方法是什么?

這是一種方法。 它使用異常來展開堆棧,並使用裝飾器來檢查每次調用遞歸時的剩余時間。

import time

class TimeRemainingExpired(Exception):
    pass

def enforce_time_remaining(f):
    """ decorator to check time remaining and raise if expired """
    def new_f(*args, **kwargs):
        if kwargs.get('_time_remaining_end_time') is None:
            kwargs['_time_remaining_end_time'] = \
                time.time() + kwargs['time_remaining']
            print(kwargs['_time_remaining_end_time'])
            print(kwargs['time_remaining'])
        if time.time() >= kwargs['_time_remaining_end_time']:
            raise TimeRemainingExpired
        return f(*args, **kwargs)

    return new_f


@enforce_time_remaining
def recurse(**kwargs):
    time.sleep(.01)
    recurse(**kwargs)

print(time.time())
try:
    recurse(time_remaining=1)
except TimeRemainingExpired:
    print('Time Expired')
print(time.time())

基本上,您需要啟動一個線程,在設定的分配時間后停止全局時間變量,然后允許您的搜索功能在之后運行並檢查該最大時間條件何時為假或某些狀態告訴您程序為否更長的假設是遞歸繼續。

這是一個遞歸函數的例子,我已經傳遞了一個迭代,所以你可以看到它並且人為地減慢它。 您需要啟動一個線程來啟動全局計時器,然后在每次調用遞歸函數時檢查該全局計時器。

import time
from threading import Thread

# create a global variable time that is ture
global_time = True 

# start the timer
def start_timer():
        time.sleep(0.1) # 1/10 second
        # Make sure you're referencing the GLOBAL time variable.
        global global_time
        # After 1/10 second, the timer will stop.
        global_time = False
        print("time stopped")

# The itteration variable is just for display.
def dfs(itteration):
        # Put your search logic here.

        # Again, make sure you're referencing the GLOBAL time variable.
        global global_time
        if global_time == True:
                # Artificially slowing down the search function.
                time.sleep(0.01)
                # Just print the iteration so you can see what's going on.
                itteration = itteration + 1 
                print(itteration)
                return dfs(itteration)
        else:
                return "DONE"

# First start the timer.
timer_thread = Thread(target = start_timer)
timer_thread.start()
# Run the search function.
print(dfs(0))

由於計時器是1/10秒,直到它為假並且每次嘗試將需要1/100,它應該只運行10次。 這是我的結果:

python time.py 
1
2
3
4
5
6
7
8
9
time stopped
DONE

重要的是你使用global或者dfs函數不會知道global_time是你在第4行設置的那個並且它會永遠持續下去。

注意我的python版本是3.5,並且2.7版本中的線程可能不同。

無關的說明:DFS非常低效。 你應該使用BFS( 廣度優先搜索 )或A *搜索 (證明是最優的 ),盡管這與問題無關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM