题解 | 坐标移动

坐标移动

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

import sys

while True:
    try:
        str=input().split(';')
        x,y=0,0
        for item in str:
            if item!='' and (item[0] in ['A', 'D', 'W', 'S']):
                try:
                    # 提取距离
                    dis = int(item[1:])
                    # 检查距离是否在合法范围内
                    if 1 <= dis <= 99:
                        # 根据指令更新坐标
                        if item[0] == 'A':
                            x -= dis
                        elif item[0] == 'D':
                            x += dis
                        elif item[0] == 'W':
                            y += dis
                        elif item[0] == 'S':
                            y -= dis
                except :
                    # 如果转换失败,跳过当前指令
                    continue  
        print(f"{x},{y}")
            
    except EOFError:
        # 捕获EOFError,退出循环
        break
    except Exception as e:
        # 捕获其他异常,打印错误信息并继续
        print(f"发生错误:{e}")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务