题解 | 坐标移动

坐标移动

https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29

import sys


def is_valid_direction(d):
    return d in ["A", "D", "W", "S"]


def main():
    # 读取输入
    s = sys.stdin.readline().strip()

    # 分割指令,[:-1]去掉最后一个空字符串(因为末尾有分号)
    commands = s.split(";")[:-1]

    x, y = 0, 0  # 初始坐标

    for cmd in commands:
        # 指令至少要有2个字符(方向和至少一位数字)
        if len(cmd) < 2:
            continue

        direction = cmd[0]
        num_str = cmd[1:]

        # 检查方向是否合法
        if not is_valid_direction(direction):
            continue

        # 检查剩余部分是否都是数字
        if not num_str.isdigit():
            continue

        # 转换为整数并检查范围
        distance = int(num_str)
        if distance <= 0 or distance >= 100:
            continue

        # 根据方向移动
        if direction == "A":  # 向左
            x -= distance
        elif direction == "D":  # 向右
            x += distance
        elif direction == "W":  # 向上
            y += distance
        elif direction == "S":  # 向下
            y -= distance

    # 输出结果
    print(str(x) + ',' + str(y))


if __name__ == "__main__":
    main()

# 容易忘记最后一个';'

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务