简体   繁体   中英

Given coordinates of pawns on a chess board, Count 'safe pieces', Python

Given the coordinates of pawns on a chess board, represented as a set of strings ie. {"b4", "d4", "f4", "c3", "e3", "g5", "d2"}, where the board is represented by rows as digits, and columns as alpha characters. determine the number of protected pawns, ie the number of pawns with other pawns diagonally behind them on the board. I am trying to teach myself python and have been at this task for hours. Any help would be greatly appreciated. Here is my embarrassingly messy attempt:

def safe_pawns(pawns):
    count = 0
    cols = "abcdefgh"
    positions = {'a':[],'b':[],'c':[],'d':[],'e':[],'f':[],'g':[],'h':[]}
    for i in positions:
        for j in pawns:
            if i in j:
                positions[i].append(int(j[1]))
    for k in range(len(cols)-1):
        for l in positions[cols[k+1]]:
            if l +1 or l-1 in positions[cols[k]]:
                count +=1
    return count

I'm willing to bet this is your problem:

if l +1 or l-1 in positions[cols[k]]:

This doesn't mean "if l+1 is in that slot, or l-1 is in that slot". If you meant that (and you almost certainly did), you have to say that:

if l+1 in positions[cols[k]] or l-1 in positions[cols[k]]:

(There are various ways to write it indirectly, too, like if {l+1, l-1}.intersection(positions[cols[k]]) , but I think the explicit version is the obvious way here.)

First, using letters for columns is going to cause you problems once you start doing arithmetic because you cant just do 'b' - 1 . It will be easier if you convert your set from a set of strings like 'a1' into a set of tuples like (1, 1) . (Or you could zero-index, but that is outside the scope here I think).

Second, let's assume you now have a pawns set {(2, 4), (3, 3), (4, 2), (4, 4), (5, 3), (6, 4), (7, 5)} . You don't need that much looping. You can actually get the set of protected pieces (I'm assuming you're going from the "bottom" of the board player?) using a set expression:

{(x,y) for (x,y) in s if (x-1,y-1) in s or (x+1,y-1) in s}

And you'll find the size of that is 6.

Note: the input conversion expression I used was:

s = {("abcdefg".find(let) + 1, int(num)) for let, num in pawns}

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