华为机考入门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)
相关推荐
To_OC11 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC11 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
BadBadBad__AK13 小时前
线段树维护区间 k 次方和
c++·数学·算法·stl
Warson_L18 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅18 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅18 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L18 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅18 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L19 小时前
python的类&继承
python
Warson_L19 小时前
类型标注/type annotation
python