题解 | 坐标移动

坐标移动

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()

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

全部评论

相关推荐

白火同学:1、简历可以浓缩成一页,简历简历先要“简”方便HR快速过滤出有效信息,再要“历”用有效信息突出个人的含金量。 2、教育背景少了入学时间~毕业时间,HR判断不出你是否为应届生。 3、如果你的平台账号效果还不错,可以把账号超链接或者用户名贴到对应位置,一是方便HR知道你是具体做了什么内容的运营,看到账号一目了然,二是口说无凭,账号为证,这更有说服力。
面试被问期望薪资时该如何...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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