[AlgorithmQuiz/MineSweeper] [Python]으로 풀면 --[yong27], 2004-09-14
1 import unittest
2
3 def capsizeCell(aMap, (i,j)):
4 nMine = 0
5 for x in range(3):
6 for y in range(3):
7 if x==y==1: continue
8 try:
9 if aMap[i-1+x][j-1+y] == '*':
10 nMine+=1
11 except IndexError:
12 continue
13 return str(nMine)
14
15 def sweepMines(aMap):
16 result = list()
17 for i,line in enumerate(aMap):
18 newline = list()
19 for j,each in enumerate(line):
20 if aMap[i][j] == '*':
21 neweach = '*'
22 else:
23 neweach = capsizeCell(aMap,(i,j))
24 newline.append(neweach)
25 result.append(''.join(newline))
26 return result
27
28 class MineSweeperTest(unittest.TestCase):
29 def testExample(self):
30 inp = [
31 '*...',
32 '....',
33 '.*..',
34 '....',
35 ]
36 expected = [
37 '*100',
38 '2210',
39 '1*10',
40 '1110',
41 ]
42 self.assertEquals(expected, sweepMines(inp))
43
44 if __name__=='__main__':
45 unittest.main(argv=('','-v'))
46
- 다음의 테스트를 통과 못합니다. --Anonymous
1 def testExample2(self): 2 inp = [ 3 '*....', 4 '.....', 5 '.*...', 6 '....*' 7 ] 8 9 expected = [ 10 '*1000', 11 '22100', 12 '1*111', 13 '1111*' 14 ] 15 self.assertEquals(expected, sweepMines(inp)) 16
원인을 살펴보니, 배열 인덱스가 음수인경우가 문제더라고요. 윗테스트를 통과하기 위해서는 capsizeCell함수를 좀 변경해야 합니다.
1 def capsizeCell(aMap, (i,j)):
2 nMine = 0
3 for x in range(3):
4 for y in range(3):
5 cursor_x = i-1+x
6 cursor_y = j-1+y
7 try:
8 if cursor_x >= 0 and cursor_y >= 0 and aMap[cursor_x][cursor_y] == '*':
9 nMine+=1
10 except IndexError:
11 continue
12 return str(nMine)
13
다른 비슷한 문제에서도 한번 생각해볼 문제인것같습니다. 음수인덱스가 가리키는 것이 뒤에서부터 세는 [Python]의 배열처리가 편하다고만 여겼었는데, 이럴 수도 있군요. IndexError 내야했더라고 착각했습니다. 지적감사합니다. --[yong27], 2005-01-21
BioHackersNet