题解 | 坐标移动

def final_position(s):
    # 初始位置
    x, y = 0, 0

    # 按';'分割指令
    commands = s.split(';')

    # 方向映射
    direction_map = {
        'A': (-1, 0),  # 左移
        'D': (1, 0),  # 右移
        'W': (0, 1),  # 上移
        'S': (0, -1)  # 下移
    }

    # 遍历每个指令
    for command in commands:
        # 忽略空指令
        if not command:
            continue
        # 第一个字符要符合条件
        direction = command[0]
        if direction not in ['A', 'S', 'D', 'W']:
            continue
        # 提取距离
        distance_str = command[1:]  # 去掉第一个字符,提取后面的数字字符串
        # 计算移动距离
        if distance_str.isdigit() and 1 <= int(distance_str) <= 99:
            distance = int(distance_str)
        else:
            continue
        # 获取移动方向的增量
        dx, dy = direction_map[direction]

        # 更新位置
        x += dx * distance
        y += dy * distance

    # 返回最终位置
    return x, y

# 读取输入
s = input().strip()

# 计算并输出最终位置
x, y = final_position(s)
print(f"{x},{y}")

全部评论

相关推荐

11-04 10:30
已编辑
门头沟学院 研发工程师
开心小狗🐶:“直接说答案”
点赞 评论 收藏
分享
迷茫的大四🐶:干脆大厂搞个收费培训得了,这样就人均大厂了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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