简体   繁体   中英

Chess movement, running out of memory python loops

I was tasked with calculating all the potential positions a knight can take, when starting at (0,0). I am a beginner so my code is clunky, but it seems to work for a smaller set of iterations. As soon as I get 8-9 steps deep, I run out of memory.

def moves(pos):
    re=[[]]
    for i in range(0,len(pos)):
        x,y=pos[i]
        a=[x+2,y+1]
        b=[x+2,y-1]
        c=[x-2,y+1]
        d=[x-2,y-1]
        e=[x+1,y+2]
        f=[x+1,y-2]
        g=[x-1,y+2]
        h=[x-1,y-2]
        re.append(a)
        re.append(b)
        re.append(c)
        re.append(d)
        re.append(e)
        re.append(f)
        re.append(g)
        re.append(h)
    del re[0]
    return re
def clean(a):
    cmoves=[]
    for i in range(0,len(a)):
        if a[i][0]>-1 and a[i][1]>-1 and a[i][0]<9 and a[i][1]<9 :
            cmoves.append(a[i])
    return cmoves 
def comb(a):
   return clean(moves(a))
pos= [[0,0]]  
a=comb(res)
steps_count=10
for step in range(steps_count):
    res=comb(res)  

Any help or tip is highly appreciated, thank you.

In clean , also remove duplicate positions. You can use a set to keep track of which positions you've seen before, if you convert the coordinates to use tuple s instead of list s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM