Click here for questions and answers from others http://qiita.com/mtsmfm/items/6d9112fcc568908caaba
path is a mountain trail. A two-dimensional array of [top to foot stairs (number of sideways + 1)] for each ["A" to "H"].
The contents of path are 0
for the stairs that go straight up, + 1
for the stairs that move to the right mountain trail, -1
for the stairs that move to the left mountain trail, and None
for the stairs that cannot be passed due to falling rocks. ..
step is the position of the stairs. The top is [0]
and the base is [-1]
(last element).
direction is the direction of the side street. 1-8.
across is a string that represents the order and direction of the sideways.
place and rock are the positions of the mountain trails. "A"-"H".
index is the position to climb / descend. 0-7 (index number corresponding to "A"-"H").
# -*- coding:utf-8 -*-
PATH = "ABCDEFGH"
def make_path(across):
path = [[0] * (len(across) + 1) for i in xrange(len(PATH))]
for step, direction in enumerate(across):
index = int(direction) % len(PATH)
path[index+0][step] = -1
path[index-1][step] = +1
return path
def fall_rock(path, index):
for step in xrange(len(path[0])):
next_index = (index + path[index][step]) % len(PATH)
path[index][step] = None
index = next_index
def climb(path, index):
for step in xrange(len(path[0]) - 1, -1, -1):
if path[index][step] is None:
return False
index = (index + path[index][step]) % len(PATH)
return True
def solve(data):
across, rock = data.split(':')
path = make_path(across)
fall_rock(path, PATH.index(rock))
climbable_places = [place
for index, place in enumerate(PATH)
if climb(path, index)]
return ''.join(climbable_places)
if __name__ == '__main__':
testdata = (
(0, "2512:C", "DEFGH"),
(1, "1:A", "CDEFGH"),
(2, ":C", "ABDEFGH"),
(3, "2345:B", "AGH"),
(4, "1256:E", "ABCDH"),
(5, "1228:A", "ADEFG"),
(6, "5623:B", "AEFGH"),
(7, "8157:C", "ABDEFGH"),
(8, "74767:E", "ABCFGH"),
(9, "88717:D", "ABCEFGH"),
(10, "148647:A", "ACDEFH"),
(11, "374258:H", "BCDEFH"),
(12, "6647768:F", "ABCDEH"),
(13, "4786317:E", "ABFGH"),
(14, "3456781:C", ""),
(15, "225721686547123:C", "CEF"),
(16, "2765356148824666:F", "ABCDEH"),
(17, "42318287535641783:F", "BDE"),
(18, "584423584751745261:D", "FGH"),
(19, "8811873415472513884:D", "CFG"),
(20, "74817442725737422451:H", "BCDEF"),
(21, "223188865746766511566:C", "ABGH"),
(22, "2763666483242552567747:F", "ABCG"),
(23, "76724442325377753577138:E", "EG"),
(24, "327328486656448784712618:B", ""),
(25, "4884637666662548114774288:D", "DGH"),
(26, "84226765313786654637511248:H", "DEF"),
(27, "486142154163288126476238756:A", "CDF"),
(28, "1836275732415226326155464567:F", "BCD"),
(29, "62544434452376661746517374245:G", "G"),
(30, "381352782758218463842725673473:B", "A"),
)
def test():
for no, data, correct in testdata:
answer = solve(data)
print '%s #%d "%s" "%s" -> "%s"' % (('NG!!','OK ')[answer == correct], no, data, correct, answer)
test()
Recommended Posts