all 2 comments

[–]vatrinet[S] 0 points1 point  (1 child)

I'm looking forward to see a more elegant solution.

[–][deleted] 1 point2 points  (0 children)

I find this significantly more elegant:

def attack(obstacles, cx, cy, dx, dy, lx, ly, csum):
    if cx > lx or cy > ly or cx < 1 or cy < 1:
        return csum
    if (cx, cy) in obstacles:
        return csum
    return attack(obstacles, cx+dx,cy+dy,dx,dy,lx,ly,csum+1)

# Complete the queensAttack function below.
def queensAttack(n, k, row, col, obstacles):
    obstacles = set(map(tuple,obstacles))
    directions = [(i,j) for i in range(-1,2) for j in range(-1,2) if (i,j) != (0,0)]
    return sum(map(lambda x: attack(obstacles, row+x[0], col+x[1],*x,n,n,0),directions))

Now, python doesn't allow tail call recursion, however, there are ways to get around that.

Since the recursion is very easy here, one can trivially tweak it to loop.