题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
def calculate_coordinates(s): x,y = 0,0 coordinates = s.split(';') for coordinate in coordinates: if len(coordinate) < 2: continue direction = coordinate[0] num = coordinate[1:] if not num.isdigit(): continue if direction == 'A': x -= int(num) elif direction == 'W': y += int(num) elif direction == 'D': x += int(num) elif direction == 'S': y -= int(num) return x, y s = input() result = calculate_coordinates(s) print(",".join(str(coord) for coord in result))
将算法定义为函数,函数输入为字符串s,首先用split分割,初始化坐标位置x,y,再判断坐标长度>2,接着获取方向direction,以及数字(如果数字部分不是digit则跳过,最后根据方向+-坐标。调用:获取input,调用函数计算,使用‘,’.join连接输出坐标x,y
#华为机试HJ17#