簡體   English   中英

Python 2.7.3中的內存錯誤

[英]Memory Error in Python 2.7.3

我正在嘗試在python上運行該程序,該程序模擬了在太空中無意識地移動並查看它是否會達到目標。.但是我每次運行它都會遇到內存錯誤。

init_posn=[0,0]
posn_final=[2,2]

obs = [[-1,1],[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1]]

# algo can be improved

def obs_det(posn_x,posn_y,obs):
    for e in obs:
        if e[0]==posn_x & e[1]==posn_y:
            return 1
    return 0

posn=[]
posn.append(init_posn)

def posn_progress(posn,posn_final,obs):
    i=0
    non=0
    while (non==0 | (posn[i][0]==posn_final[0] & posn[i][1]==posn_final[1])):
        l=posn[i][0]
        m=posn[i][1]
        if obs_det(l,m+1,obs) == 0:
            posn.append([l,m+1])
        elif obs_det(l+1,m,obs) == 0:
            posn.append([l+1,m])
        elif obs_det(l,m-1,obs) == 0:
            posn.append([l,m-1])
        elif obs_det(l-1,m,obs) == 0:
            posn.append([l-1,m])
        else:
            non=1
        i=i+1
    if non==1:
        return 0
    else:
        return posn

print posn_progress(posn,posn_final,obs)

因為這看起來像是作業,所以我將給出兩個提示:

  1. 您將如何編寫單元測試以查看障礙物檢測例程是否按預期工作?
  2. 了解邏輯和按位運算符。

這是一些示例代碼; 它基本上從起點開始進行洪水填充,直到到達終點為止。 請注意,它會跟蹤已經seen的位置,因此不會無休止地對其進行重新探索。

dir = [(dx,dy) for dx in (-1,0,1) for dy in (-1,0,1) if (dx,dy)!=(0,0)]

def backtrack(b, seen):
    if seen[b]==0:
        return [b]
    else:
        seek = seen[b]-1
        x,y = b
        for dx,dy in dir:
            p = (x+dx, y+dy)
            if p in seen and seen[p]==seek:
                return backtrack(p, seen) + [b]

def find_path(a, b, dist=0, here=None, seen=None):
    if here is None: here = set([a])
    if seen is None: seen = {a:0}

    next = set()
    for x,y in here:
        for dx,dy in dir:
            p = (x+dx, y+dy)
            if p not in seen:
                seen[p] = dist+1
                next.add(p)

    if b in seen:   # found it!
        return backtrack(b, seen)
    else:
        return find_path(a, b, dist+1, next, seen)

def main():
    print find_path((0,0), (2,2))

if __name__=="__main__":
    main()

我認為您的盲目性正在盤旋中。

您可以教它避免回溯它的來源。 這樣它就不會循環,但是即使存在,也可能無法找到路。

或者,您可以使其更智能,然后告訴它如果返回,則下次應該嘗試其他路線。

暫無
暫無

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

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