题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
写了一个效率不高的解决方案,借助正则表达式来判定正确的字符串,使用字典来实现switch-case,希望有大佬能够帮忙优化一下。代码如下:
import re def countL(tup: tuple, k: str, v: int): return { 'A': (lambda tup: (tup[0].__sub__(v), tup[1])), 'D': (lambda tup: (tup[0].__add__(v), tup[1])), 'S': (lambda tup: (tup[0], tup[1].__sub__(v))), 'W': (lambda tup: (tup[0], tup[1].__add__(v))) }[k](tup) origin = input() pattern = re.compile(r'^[ADSW]\d{0,2}$') rawList = origin.split(';') tone = (0, 0) for op in rawList: if re.match(pattern, op): tone = countL(tone, op[0], int(op[1:])) print(f'{tone[0]},{tone[1]}')