Python自定义凯撒密码开发难题:需实现双向移位及单词首字符特殊处理
解决方案
核心逻辑拆解
要实现你的加密需求,需聚焦以下关键环节:
- 每个独立单词内部单独计数位置,首字符固定为奇数位(位置1)
- 奇数位字符ASCII值加catalyst(向上移位),偶数位字符ASCII值减catalyst(向下移位)
- 字母和数字做循环移位处理(如
Z加1回到A,0减1回到9),避免超出有效字符范围 - 每处理一个字符后,按规则更新catalyst的值
关键函数实现
首先实现字符移位工具函数,处理字母数字的循环逻辑:
def shift_char(c, catalyst, is_odd_position): shift = catalyst if is_odd_position else -catalyst if c.isupper(): # 大写字母循环移位 return chr((ord(c) - ord('A') + shift) % 26 + ord('A')) elif c.islower(): # 小写字母循环移位 return chr((ord(c) - ord('a') + shift) % 26 + ord('a')) elif c.isdigit(): # 数字循环移位 return chr((ord(c) - ord('0') + shift) % 10 + ord('0')) else: # 其他字符直接移位(可根据密码规则调整) return chr(ord(c) + shift)
接着实现核心加密逻辑,遍历每个单词并维护位置计数:
def encrypt_message(processed_sentence, initial_catalyst): catalyst = initial_catalyst catalyst_reset = 6 encrypted_words = [] for word in processed_sentence.split(" "): encrypted_chars = [] # 每个单词从位置1开始计数 for idx, char in enumerate(word, start=1): is_odd = idx % 2 == 1 encrypted_char = shift_char(char, catalyst, is_odd) encrypted_chars.append(encrypted_char) # 更新catalyst if catalyst < catalyst_reset: catalyst += 1 else: catalyst = 0 catalyst_reset += 1 encrypted_words.append("".join(encrypted_chars)) return " ".join(encrypted_words), catalyst
完整整合代码
将所有功能整合,包含你已实现的单词反转函数:
def reverseWordSentence(Sentence): words = Sentence.split(" ") newWords = [word[::-1] for word in words] return " ".join(newWords) def shift_char(c, catalyst, is_odd_position): shift = catalyst if is_odd_position else -catalyst if c.isupper(): return chr((ord(c) - ord('A') + shift) % 26 + ord('A')) elif c.islower(): return chr((ord(c) - ord('a') + shift) % 26 + ord('a')) elif c.isdigit(): return chr((ord(c) - ord('0') + shift) % 10 + ord('0')) else: return chr(ord(c) + shift) def encrypt_message(processed_sentence, initial_catalyst): catalyst = initial_catalyst catalyst_reset = 6 encrypted_words = [] for word in processed_sentence.split(" "): encrypted_chars = [] for idx, char in enumerate(word, start=1): is_odd = idx % 2 == 1 encrypted_char = shift_char(char, catalyst, is_odd) encrypted_chars.append(encrypted_char) # 更新catalyst if catalyst < catalyst_reset: catalyst += 1 else: catalyst = 0 catalyst_reset += 1 encrypted_words.append("".join(encrypted_chars)) return " ".join(encrypted_words), catalyst # 主执行流程 if __name__ == "__main__": catalyst = int(input("Catalyst: ")) mtbe = input("Message to encrypt: ") reversed_sentence = reverseWordSentence(mtbe) print("反转后的句子:", reversed_sentence) encrypted_result, final_catalyst = encrypt_message(reversed_sentence, catalyst) print("加密结果:", encrypted_result) print("最终catalyst值:", final_catalyst)
关键说明
- 单词位置计数:通过
enumerate(word, start=1)让每个单词的字符从位置1开始计数,完美满足"新单词首字符视为奇数位"的要求 - 循环移位:利用取模运算
%实现字母和数字的循环,避免移位后出现无效字符 - catalyst更新:每处理一个字符就执行一次更新逻辑,严格匹配你的规则
- 兼容性:同时支持大小写字母、数字和其他字符,可根据你的密码指南调整非字母数字的处理逻辑
内容的提问来源于stack exchange,提问作者TheNightFalxon
相关产品推荐
相关产品推荐

