【发布时间】:2016-03-15 07:40:14
【问题描述】:
我正在尝试从advent of code 解决问题,但我似乎无法破解它。它应该收集一组唯一的坐标,然后输出它们的计数。我的主要变量 coords_list 在 for 循环外实例化,然后添加到 for 内。
不过,由于某种原因,每次我在for 中附加它时,它似乎都会“重置”,所以我的返回列表最多是coords_list 的初始值列表,加上最近的我附加到它的值。
很可能我只是错过了一些简单的东西。不过,任何帮助都会很棒。
输出
coords_list: [[0, 0]]
START -- coords: [0, 0], vector: (1, 0), instruction: >
END -- coords: [1, 0], coords_list: [[0, 0], [1, 0]]
input: >, len: 2
------
coords_list: [[0, 0]]
START -- coords: [0, 0], vector: (0, 1), instruction: ^
END -- coords: [0, 1], coords_list: [[0, 0], [0, 1]]
START -- coords: [0, 1], vector: (1, 0), instruction: >
END -- coords: [1, 1], coords_list: [[0, 0], [1, 1]]
START -- coords: [1, 1], vector: (0, -1), instruction: v
END -- coords: [1, 0], coords_list: [[0, 0], [1, 0]]
START -- coords: [1, 0], vector: (-1, 0), instruction: <
END -- coords: [0, 0], coords_list: [[0, 0], [0, 0]]
input: ^>v<, len: 2
------
Traceback (most recent call last):
File "python", line 47, in <module>
AssertionError
代码
def return_vector(chary):
if chary == "^":
ret_value = (0,1)
elif chary == "v":
ret_value = (0,-1)
elif chary == ">":
ret_value = (1, 0)
elif chary == "<":
ret_value = (-1, 0)
else:
raise ValueError("Expecting one of '^','v','>','<', got {}".format(chary))
return ret_value
def main(input):
coords_list = [[0,0]]
coords = [0,0]
lst_input = list(input)
debug_iterator, debug_loop = 0, 10
print("coords_list: {}".format(coords_list))
for instruction in lst_input:
vector = return_vector(instruction)
if debug_iterator < debug_loop:
print("START -- coords: {}, vector: {}, instruction: {}".format(coords, vector, instruction))
coords[0] += vector[0]
coords[1] += vector[1]
if coords not in coords_list:
coords_list.append(coords)
if debug_iterator < debug_loop:
print("END -- coords: {}, coords_list: {}".format(coords, coords_list))
debug_iterator += 1
print('input: {}, len: {}\n------'.format(input, len(coords_list)))
return(len(coords))
assert main('>') == 2
assert main('^>v<') == 4
assert main('^v^v^v^v^v') == 2
print("main(INPUT) == {}".format(main(INPUT)))
assert return_vector('^') == (0,1)
【问题讨论】:
标签: python list for-loop append