I wanted to implement this as short and effective as I could without using anything that is not basics, in order to improve my skills.
I would appreciate input about things like memory leaks I missed, simpler way of doing things instead reinventing the wheel, methods I should have used / implemented / not implemented (could have used built-ins and defaults...) and styling. In general, does this implementation follows common best practices?
import random as r
import itertools as it
import numpy as np
class P:
up = 8
down = 0
def __init__(self,x=0,y=0,parent=None, random = False):
self.x = x if not random else r.randint(P.down,P.up-1)
self.y = y if not random else r.randint(P.down,P.up-1)
self.parent = parent
def __str__(self):
return '({},{})'.format(self.x,self.y)
def __repr__(self):
return '({},{} [{},{}])'.format(self.x,self.y,self.parent.x if self.parent else '-',self.parent.y if self.parent else '-')
def __eq__(self,other):
return self.x == other.x and self.y == other.y
# for np.unique
def __gt__(self,other):
return self.x + self.y > other.x + other.y
# for np.unique
def __lt__(self,other):
return self.x + self.y < other.x + other.y
def __hash__(self):
return hash((self.x, self.y))
def valid_moves(self):
def valid(*num):
# a better way to check if all number in num return True?
# this seems nice and short to me, but I guess there is a better way
return sum([n >= P.down and n < P.up for n in num]) // len(num)
a,b = [1,-1,],[2,-2]
# is there a way to shorten this list construction?
t = [P(self.x + i, self.y + j, self) for i in a for j in b if valid(self.x+i,self.y+j)] + [P(self.x + i, self.y + j, self) for i in b for j in a if valid(self.x+i,self.y+j)]
return np.unique(t)
s = P()
e = P(random = True)
print('findint shortest path from {} to {}'.format(s,e))
ls = s.valid_moves()
while True:
if e in ls or e == s:
print('found end node...')
#find the end node that has parents - not the
#original "e" that has no parents andt herefore
#cannot be used to generate path
curr = ls.pop(ls.index(e))
path = [curr]
print('generating path...')
while curr != s:
curr = curr.parent
path += ['->']
path += [curr]
print('path: ',path)
break
tmp = [p.valid_moves() for p in ls]
# flatten tmp into 1-d list
ls = list(it.chain(*tmp))
# Do I have any memory leaks?
del tmp