华为机考入门python3--(36)牛客36-字符串加密

分类:字符串

知识点:

  1. 判断一个元素是否在集合中 if char not in key_set

  2. 计算字母差 index = ord(char) - ord('a')

题目来自【牛客】

python 复制代码
# 生成加密表
def generate_cipher_table(key):
    key_set = set()
    cipher_table = ""

    # 去重
    for char in key:
        if char not in key_set:
            cipher_table += char
            key_set.add(char)

    # 未出现的字母按照正常字母表顺序加入新字母表
    for char in "abcdefghijklmnopqrstuvwxyz":
        if char not in key_set:
            cipher_table += char

    return cipher_table


# 使用给定的密匙加密信息
def encrypt_message(cipher_table, message):
    result = ""
    for char in message:
        # 计算索引
        index = ord(char) - ord('a')
        encrypted_char = cipher_table[index]
        result += encrypted_char
    return result

# 输入
key = input().strip()
message = input().strip()

# 生成加密表和加密信息,然后输出结果
cipher_table = generate_cipher_table(key)
encrypted_message = encrypt_message(cipher_table, message)
print(encrypted_message)
相关推荐
数模竞赛Paid answer3 小时前
2026年中青杯数学建模A题数学建模论文智能评估系统与多智能体优化方法求解全过程论文及程序
算法·数学建模·中青杯
银-豆豆3 小时前
数据结构与算法-动态规划、回溯与贪心
算法·动态规划
jufeng13074 小时前
【系列:手搓自主 AI Agent:Hermes 架构原理剖析 · 第 11 篇】
python·ai agent·mcp
想吃火锅10054 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
En^_^Joy5 小时前
Django项目配置全攻略:settings配置文件
后端·python·django
Nil2085 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
for_ever_love__5 小时前
python基础语法学习: 异常的传递性
开发语言·python·学习
AC赳赳老秦6 小时前
公开图片 OCR 数据提取:OpenClaw 合规采集公开信息图,识别文字与表格并转化为结构化数据
java·大数据·前端·数据库·python·php·openclaw
依然鸣6 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论