给定一个8*8的棋盘,同时给定8个棋子的位置。如果某一个棋子的位置可以由其他棋子一步到达,则认为该棋子安全。
一个棋子可以通过移动到那个方格,在相邻文件上的对角线前方对角线上捕捉对手的棋子。 判断8个棋子中安全的棋子的个数。 如图所示,左边的安全棋子个数为6,右边的位1。
safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6 safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1 思路:遍历给定的集合(set)里面的所有元素,然后转换为list。然后利用ord 和chr 转换求出该棋子左下和右下的棋子的位置坐标。如果该坐标在原来的集合中,则num+1。最后返回num。
def safe_pawns(pawns):
num = 0
for i in pawns:
testlist = list(i)
# b=a[0]+chr((ord(a[1])-1))
left_pos = chr(ord(testlist[0]) - 1) + chr((ord(testlist[1]) - 1))
right_pos = chr(ord(testlist[0]) + 1) + chr((ord(testlist[1]) - 1))
print(left_pos, right_pos)
if left_pos in pawns or right_pos in pawns:
num += 1
return num
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6
assert safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")