Python密码生成器项目:如何将非3倍数长度拆分为三类字符对应数量
解决方案
核心逻辑
要实现三类字符长度尽可能接近且总和等于总长度,只需通过整除取基础长度、余数分配额外长度即可:
- 计算基础长度:将总长度对3向下取整,得到三类字符的基准取值
base_len = final_pwd_length // 3 - 计算余数:得到需要额外分配1个长度的类别数量
remainder = final_pwd_length % 3 - 给余数对应数量的类别各加1,三类长度的差值最大为1,完全符合"尽可能接近"的要求,总和也刚好等于总长度
代码实现
版本1:随机分配额外长度(推荐,增强密码随机性)
import random # 可替换为任意正整数的密码总长度 final_pwd_length = 11 base_len = final_pwd_length // 3 remainder = final_pwd_length % 3 lower_length = upper_length = number_length = base_len # 随机选remainder个类别各加1个长度 add_categories = random.sample(['lower', 'upper', 'number'], k=remainder) if 'lower' in add_categories: lower_length += 1 if 'upper' in add_categories: upper_length += 1 if 'number' in add_categories: number_length += 1 # 可选:验证长度总和正确 assert lower_length + upper_length + number_length == final_pwd_length
版本2:固定顺序分配额外长度(写法更简洁)
如果不需要随机分配,也可以按固定优先级分配额外长度:
final_pwd_length = 8 base_len = final_pwd_length // 3 remainder = final_pwd_length % 3 lower_length = base_len + (1 if remainder >= 1 else 0) upper_length = base_len + (1 if remainder >= 2 else 0) number_length = base_len
效果示例
| 总长度 | 分配结果示例 | 总和 | 最大差值 |
|---|---|---|---|
| 8 | 3、3、2 | 8 | 1 |
| 11 | 4、4、3 | 11 | 1 |
| 7 | 3、2、2 | 7 | 1 |
| 9 | 3、3、3 | 9 | 0 |
内容的提问来源于stack exchange,提问作者Stefan Rows
相关产品推荐
相关产品推荐

