[AlgorithmQuiz/MineSweeper] [Python]으로 풀면 --[yong27], 2004-09-14 {{{#!python import unittest def capsizeCell(aMap, (i,j)): nMine = 0 for x in range(3): for y in range(3): if x==y==1: continue try: if aMap[i-1+x][j-1+y] == '*': nMine+=1 except IndexError: continue return str(nMine) def sweepMines(aMap): result = list() for i,line in enumerate(aMap): newline = list() for j,each in enumerate(line): if aMap[i][j] == '*': neweach = '*' else: neweach = capsizeCell(aMap,(i,j)) newline.append(neweach) result.append(''.join(newline)) return result class MineSweeperTest(unittest.TestCase): def testExample(self): inp = [ '*...', '....', '.*..', '....', ] expected = [ '*100', '2210', '1*10', '1110', ] self.assertEquals(expected, sweepMines(inp)) if __name__=='__main__': unittest.main(argv=('','-v')) }}} 다음의 테스트를 통과 못합니다. --Anonymous {{{#!python def testExample2(self): inp = [ '*....', '.....', '.*...', '....*' ] expected = [ '*1000', '22100', '1*111', '1111*' ] self.assertEquals(expected, sweepMines(inp)) }}} ---- 원인을 살펴보니, 배열 인덱스가 음수인경우가 문제더라고요. 윗테스트를 통과하기 위해서는 capsizeCell함수를 좀 변경해야 합니다. {{{#!python def capsizeCell(aMap, (i,j)): nMine = 0 for x in range(3): for y in range(3): cursor_x = i-1+x cursor_y = j-1+y try: if cursor_x >= 0 and cursor_y >= 0 and aMap[cursor_x][cursor_y] == '*': nMine+=1 except IndexError: continue return str(nMine) }}} 다른 비슷한 문제에서도 한번 생각해볼 문제인것같습니다. 음수인덱스가 가리키는 것이 뒤에서부터 세는 [Python]의 배열처리가 편하다고만 여겼었는데, 이럴 수도 있군요. IndexError 내야했더라고 착각했습니다. 지적감사합니다. --[yong27], 2005-01-21