华为机考入门python3--(17)牛客17- 坐标移动

分类:字符串

知识点:

  1. 正则匹配       re.match(pattern, move)

  2. 格式字符串,可以在字符串中直接引用变量    f"{x},{y}"

题目来自【牛客】

图片


import re  
  
def is_valid_coordinate(move):  
    # 使用正则表达式验证移动是否合法  
    # ^: 表示字符串的开始。
    # [ADWS]: 匹配一个字符,该字符必须是 A、D、W 或 S 中的一个。
    # [0-9]{1,2}: 匹配 1 到 2 个数字。[0-9] 表示匹配任意一个数字,{1,2} 表示前面的数字可以重复 1 到 2 次。
    # $: 表示字符串的结束。
    pattern = r'^[ADWS][0-9]{1,2}$' 
    # 返回匹配则返回<re.Match object; span=(0, 3), match='A12'> 
    # 没有则返回None
    return re.match(pattern, move) is not None  
  
def calculate_coordinates(input_string):  
    # 初始化坐标为原点  
    x, y = 0, 0  
      
    # 遍历输入字符串中的每个字符  
    moves = input_string.split(';')  
    for move in moves:  
        # 检查移动是否有效  
        if is_valid_coordinate(move):  
            # 获取移动方向和距离  
            direction = move[0]  
            distance = int(move[1:])  # 距离为输入字符串的剩余部分,不需要额外验证  
            # 根据方向移动对应的距离  
            if direction == 'A':  # 向左移动  
                x -= distance  
            elif direction == 'D':  # 向右移动  
                x += distance  
            elif direction == 'W':  # 向上移动  
                y += distance  
            elif direction == 'S':  # 向下移动  
                y -= distance  
        else:  
            # 如果移动无效,忽略它  
            pass  
    return f"{x},{y}"  # 返回最终的坐标,格式化为字符串  
  
# input_string = "A10;S20;W10;D30;X;A1A;B10A11;;A10;"  
input_string = input().strip()
output_string = calculate_coordinates(input_string)  
print(output_string)  # 输出:10, -10

 

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 09:14:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 09:14:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 09:14:05       82 阅读
  4. Python语言-面向对象

    2024-04-23 09:14:05       91 阅读

热门阅读

  1. 每天一个数据分析题(二百八十四)

    2024-04-23 09:14:05       34 阅读
  2. 关于抖音 担保支付 订单同步 报错

    2024-04-23 09:14:05       36 阅读
  3. WordPress 谷歌SEO是否还有必要做?又该如何做?

    2024-04-23 09:14:05       36 阅读
  4. RabbitMQ传递序列化/反序列化自定义对象时踩坑

    2024-04-23 09:14:05       37 阅读
  5. Edge浏览器的深度探索与使用心得

    2024-04-23 09:14:05       40 阅读
  6. LRU缓存(哈希+双链表)

    2024-04-23 09:14:05       43 阅读
  7. Spring Cloud 面试题(七)

    2024-04-23 09:14:05       35 阅读
  8. 在 Oracle 数据库中使用正则表达式

    2024-04-23 09:14:05       36 阅读
  9. 【Web前端笔记14】函数与对象

    2024-04-23 09:14:05       35 阅读
  10. IDM激活_powershelll

    2024-04-23 09:14:05       33 阅读
  11. MyBatis 面试题(六)

    2024-04-23 09:14:05       30 阅读