我有这个密码生成器,它从包含小写字母、大写字母和数字(不含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
结果的百分比(,一切都能正常工作。
删除了try:
,因为您没有使用expect
处理任何错误。同样删除了elif:
,无论如何都不会满足这个条件。此外,你的comb_numb
公式不是正确的,因为你正在生成具有重复的组合。有了这些更改,您的代码就很好了。
import math, iterations, string
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
comb_numb = len(characters) ** k
x = 0
# first value
percent = 5
# step of percent done to display
step = 5
# 'step' % of combinations
boundary_value = comb_numb/(100/step)
# 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:
print("{} % complete".format(percent))
percent += step
boundary_value += comb_numb/(100/step)
pw_gen(string.ascii_letters, 4)