06.Pawn Brotherhood

任務:

Almost everyone in the world knows about the ancient game Chess and has at least a basic understanding of its rules. It has various units with a wide range of movement patterns allowing for a huge number of possible different game positions (for example Number of possible chess games at the end of the n-th plies.) For this mission, we will examine the movements and behavior of chess pawns.

Chess is a two-player strategy game played on a checkered game board laid out in eight rows (called ranks and denoted with numbers 1 to 8) and eight columns (called files and denoted with letters a to h) of squares. Each square of the chessboard is identified by a unique coordinate pair — a letter and a number (ex, "a1", "h8", "d6"). For this mission we only need to concern ourselves with pawns. A pawn may capture an opponents piece on a square diagonally in front of it on an adjacent file, by moving to that square. For white pawns the front squares are squares with greater row than their.

A pawn is generally a weak unit, but we have 8 of them which we can use to build a pawn defense wall. With this strategy, one pawn defends the others. A pawn is safe if another pawn can capture a unit on that square. We have several white pawns on the chess board and only white pawns. You should design your code to find how many pawns are safe.

You are given a set of square coordinates where we have placed white pawns. You should count how many pawns are safe.

Input: Placed pawns coordinates as a set of strings.

Output: The number of safe pawns as a integer.

Example:

safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6nsafe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1n


我的代碼:

def safe_pawns(pawns):n num = 0n for i in pawns:n C = chr(ord(i[1])-1)n L = chr(ord(i[0])-1)n R = chr(ord(i[0])+1)n CL = str(L+C)n CR = str(R+C)n if CL in pawns or CR in pawns:n num += 1n return numn


來,神們的:

第一個: Clear

def safe_pawns(pawns):n answer = 0n for pawn in pawns :n if chr(ord(pawn[0])-1)+str(int(pawn[1])-1) in pawns or chr(ord(pawn[0])+1)+str(int(pawn[1])-1) in pawns : answer +=1n return answern

第二個:還是Clear的,別的組沒有。

def getdiags(pawn):n c, r = map(ord, pawn)n return chr(c - 1) + chr(r - 1), chr(c + 1) + chr(r - 1)nndef safe_pawns(pawns):n return len([p for p in pawns if any(d in pawns for d in getdiags(p))])n

恩,多少有點平衡。都差不多。而且,沒有創意分類的。

是不是問題太容易造成的呢?

推薦閱讀:

在同一台電腦下如何進行 Python 2 與 3 的切換?
哪些庫是 Python2 獨有而 Python3 暫時不支持的?
你看好 Python 3 嗎?
python3是如何處理字元異常的?
為什麼Python第三方庫的document看起來很統一?

TAG:Python | Python入门 | Python3x |