所以我刚刚注册了hackerrank,并尝试了第一个AI问题,其中涉及通过网格搜索找到Peach公主,然后打印出机器人马里奥应该采取的步骤来拯救她。这是我的代码:
def displayPathtoPrincess(n,grid):
MOVES = ['LEFT','RIGHT','UP','DOWN']
m,p = (i for i,x in enumerate(grid) if x != '-')
if grid[m] == 'p': m,p = p,m
m,p = ((x/m, x%m) for x in [m,p])
if m[0] > p[0]: v = 2
else: v = 3
if m[1] > p[1]: h = 0
else: h = 1
path = [v] * abs(m[0] - p[0])
path.extend([h]*abs(m[1]-m[1]))
return '\n'.join([MOVES[p] for p in path])
当我运行代码时,我收到一个 ValueError:
Traceback (most recent call last):
File "/game-player1-ooQVK8ZfwGFijjFs07eCIWom4Z3NG8W3/solution.py", line 26, in <module>
displayPathtoPrincess(m,grid)
File "/game-player1-ooQVK8ZfwGFijjFs07eCIWom4Z3NG8W3/solution.py", line 5, in displayPathtoPrincess
m,p = (i for i,x in enumerate(grid) if x != '-')
ValueError: too many values to unpack
不完全确定我做错了什么,因为我认为 enumerate 返回网格内的值以及索引,所以它不像我试图将一个值分配给两个变量。这个修复可能很容易。提前致谢!