我有一個問題。我正在編寫一個數獨求解器,例如,對於A1的平方,我想查找子網格中的9個相鄰方塊的列表(A1,A2,A3,B1,B2,B3,C1,C2,C3)如果在該元素中找到某個字符,返回列表元素的Python方法
我的計劃是在A和1中分割A1,然後返回'ABC'和'123'的叉積,但如果square [0] ='A',我無法弄清楚如何優雅地返回'ABC'。
我想找到一個優雅的方式來返回從一組列表中找到元素的列表。 ['ABC','DEF','GHI'],當我輸入A時,我想得到字符串'ABC'。
的完整代碼大氣壓:
def cross_product(A, B):
"""Returns a list of the cross product of A and B."""
return [a+b for a in A for b in B]
rows = 'ABCDEFGHI'
cols = '123456789'
squares = cross_product(rows, cols) # List of 81 squares
def find_row(square):
"""
Returns list of strings with corresponding row values.
Example: find_row('A2') -> ['A1','A2', ..., 'A9']
"""
return cross_product(square[0], cols)
def find_col(square):
"""
Returns list of strings with corresponding col values.
Example: find_col('A2') -> ['A2','B2', ..., 'I2']
"""
return cross_product(rows, square[1])
def find_peers(square):
"""
Returns list of strings of shared squares in the unit.
Example: find_peers('A2') -> ['A1', 'A2', 'A3', 'B1' , ..., 'C3']
"""
for e in ['ABC','DEF','GHI']:
if square[0] in e:
r = e
for e in ['123','456','789']:
if square[1] in e:
c = e
return cross_product(r, c)
有沒有什麼辦法讓find_peers(方形)更Python?
謝謝。這肯定看起來Pythonic。 (Bedankt,Martijn!) – Rainymood