华为机考入门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)
相关推荐
工頁光軍8 分钟前
基于Python的Milvus完整使用案例
开发语言·python·milvus
Csvn9 分钟前
特殊方法与运算符重载
python
fff98111815 分钟前
C++与Qt图形开发
开发语言·c++·算法
xht083226 分钟前
PHP vs Python:编程语言终极对决
开发语言·python·php
计算机安禾30 分钟前
【数据结构与算法】第3篇:C语言核心机制回顾(二):动态内存管理与typedef
c语言·开发语言·数据结构·c++·算法·链表·visual studio
2401_8796938737 分钟前
使用Python控制Arduino或树莓派
jvm·数据库·python
查古穆1 小时前
python进阶-推导式
开发语言·python
njidf1 小时前
C++中的访问者模式
开发语言·c++·算法
☆5661 小时前
如何为开源Python项目做贡献?
jvm·数据库·python