写一个名为direction(path)的函数,其中path是一个包含移动方向的string。这个函数验证给定的路径是否能让旅行者返回到他们开始的地方。如果路径是有效的旅程,它应该print True,如果不是,则print False。输入的路径将使用'N'代表北,'S'代表南,'E'代表东,'W'代表西。每一个路径都会用空格隔开。例如,如果你的路径是往北走,然后往东走,路径将是 "N E"。
且空格路径“ ” 是无效路径
请用以下的例子来进行检验:
“E W” True
“E S” False
“NESW”True
“NNNESSS”False
def check(str):
(x, y) = (0, 0)
for s in str:
if s == 'S':
y += 1
elif s == 'N':
y -= 1
elif s == 'E':
x += 1
elif s == 'W':
x -= 1
if (x == 0) and (y == 0):
print('True')
else:
print('False')
def direction(path: str):
return path.count('W') == path.count('E') and path.count('N') == path.count('S')
print(direction('E W'))
print(direction('E S'))
print(direction('N E S W'))
print(direction('N N N E S S S'))
您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632