我有这个python代码,用于指示 m 以达到 p 。
以下是代码:
#!/bin/python
def displayPathtoPrincess(n,grid):
m = "m"
p = "p"
for i in range(n):
if(m in grid[i]):
m_column = grid[i].find(m)
m_row = int(i + 1)
#print "{0}x{1} \n".format(int(i + 1), m_position + 1)
if(p in grid[i]):
p_column = grid[i].find(p)
p_row = int(i + 1)
#print "{0}x{1} \n".format(int(i + 1), p_position + 1)
down_up = p_row - m_row
if(down_up > 0):
print "DOWN\n"*down_up
else:
print "UP\n"
right_left = p_column - m_column
if(right_left > 0):
print "RIGHT\n"*right_left
else:
print "LEFT\n"
m = input()
grid = []
for i in xrange(0, m):
grid.append(raw_input().strip())
displayPathtoPrincess(m,grid)
输入:
> 6
> ---
> ---
> -m-
> ---
> ---
> p--
预期产出:
DOWN
DOWN
DOWN
LEFT
我的输出:
DOWN
DOWN
DOWN
LEFT
正如您在输出中看到的那样,程序在改变方向时会添加一个新行。关于如何阻止这条新线出现的任何想法?
答案 0 :(得分:0)
每次执行此操作后,您都会在每个'DOWN'
或'RIGHT'
之后对换行符进行硬编码:
print "DOWN\n"*down_up
print "RIGHT\n"*right_left
结果字符串将是'DOWN'
或'RIGHT'
,后跟换行符,指定的次数。这意味着此类字符串将以不需要的换行结束。最小的修复是将所需数量乘以少于1,然后添加最后一位:
print "DOWN\n"*(down_up-1) + 'DOWN'
print "RIGHT\n"*(right_left-1) + 'RIGHT'
或使用str.join
:
print '\n'.join("DOWN" for i in range(down_up))
print '\n'.join("RIGHT" for i in range(right_left))