我有这个密码生成器,它可以将包含小写字母,大写字母和数字(不包含0)的列表中2到6个字符的长度组合-总共61个字符。
我所需要的是显示已经创建的组合的百分比(以5为步长)。我尝试计算所有选定长度的组合,从该数字开始计算一个边界值(5%步进值),并计算写入文本文件的每个组合,当组合数量达到边界值时,打印xxx % completed
,但是此代码似乎无效。
您知道如何轻松显示百分比吗?
对不起,我的英语,我不是母语人士。
谢谢大家!
def pw_gen(characters, length):
"""generate all characters combinations with selected length and export them to a text file"""
# counting number of combinations according to a formula in documentation
k = length
n = len(characters) + k - 1
comb_numb = math.factorial(n)/(math.factorial(n-length)*math.factorial(length))
x = 0
# first value
percent = 5
# step of percent done to display
step = 5
# 'step' % of combinations
boundary_value = comb_numb/(100/step)
try:
# output text file
with open("password_combinations.txt", "a+") as f:
for p in itertools.product(characters, repeat=length):
combination = ''.join(p)
# write each combination and create a new line
f.write(combination + '\n')
x += 1
if boundary_value <= x <= comb_numb:
print("{} % complete".format(percent))
percent += step
boundary_value += comb_numb/(100/step)
elif x > comb_numb:
break
首先-我认为您使用的组合公式不正确,因为itertools.product
会产生重复变化,因此正确的公式为n ^ k(n为k的幂)。>>
而且,您对百分比的计算有些复杂。我只是修改了您的代码以使其按预期工作。
import math import itertools def pw_gen(characters, length): """generate all characters combinations with selected length and export them to a text file""" k = length n = len(characters) comb_numb = n ** k x = 0 next_percent = 5 percent_step = 5 with open("password_combinations.txt", "a+") as f: for p in itertools.product(characters, repeat=length): combination = ''.join(p) # write each combination and create a new line f.write(combination + '\n') x += 1 percent = 100.0 * x / comb_numb if percent >= next_percent: print(f"{next_percent} % complete") while next_percent < percent: next_percent += percent_step
棘手的部分是
while
循环,可确保对于很小的集合(其中一个组合大于结果的step
百分比),一切正常。