Python实现指定长度密码穷举及平方根算法性能对比
本文介绍使用Python递归生成指定长度字符串的穷举方法,并对比穷举法、二分法与牛顿-拉夫逊法求解平方根的性能。测试显示,穷举法耗时超过1分钟,二分法不足1秒,而牛顿-拉夫逊法实现秒级响应,展示了不同算法在计算效率上的显著差异。
该程序基于提供的字符字典,能够穷举出所有指定长度的字符串组合:
def get_pwd(str, num):
if(num == 1):
for x in str:
yield x
else:
for x in str:
for y in get_pwd(str, num-1):
yield x+y
strKey="abc"
for x in get_pwd(strKey,3):
print x
运行结果如下:
aaa aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc caa cab cac cba cbb cbc cca ccb ccc
此程序具有内存占用低、生成速度快的特点,欢迎实际测试。
补充知识:Python中穷举法、二分法与牛顿-拉夫逊方法在求解平方根时的性能对比分析
从性能优劣角度来看,求解平方根的方法从左至右依次递进优化。
经实测,穷举法耗时基本超过1分钟,至今未输出结果;
二分法仅需不到1秒即可得出结果。
牛顿-拉夫逊法则实现秒级输出,过程无停顿。
numberTarget =int(input("Please enter a number:"))
numberSqureRoot = 0
while(numberSqureRoot<abs(numberTarget)):
if numberSqureRoot**2 >= abs(numberTarget):
break
numberSqureRoot = numberSqureRoot + 1
if numberSqureRoot**2 != numberTarget:
print("Your number %s is not a perfect squre, the square root is %s " % ( numberTarget,numberSqureRoot) )
else:
if numberTarget < 0 :
numberSqureRoot = -numberSqureRoot
print("Your number %s is a perfect squre, the square root is %s " % ( numberTarget, numberSqureRoot))
print("now we begin to calculate the binary search...")
numberTarget=int(input("Please enter the number for binary search..."))
numberSqureRoot = 0
lowValue = 0.0
highValue=numberTarget*1.0
epsilon = 0.01
numberSqureRoot = (highValue + lowValue)/2
while abs(numberSqureRoot**2 - numberTarget) >=epsilon:
print("lowValue:%s, highValue:%s, currentValue:%s"%(lowValue,highValue,numberSqureRoot))
if numberSqureRoot**2<numberTarget:
lowValue=numberSqureRoot
else:
highValue=numberSqureRoot
numberSqureRoot = (lowValue+highValue) /2
print("The number %s has the squre root as %s " %(numberTarget,numberSqureRoot))
print("now we begin to calculate the newTon search...")
numberTarget=int(input("Please enter the number for newTon search..."))
numberSqureRoot = 0
epsilon = 0.01
k=numberTarget
numberSqureRoot = k/2.0
while( abs(numberSqureRoot*numberSqureRoot - k)>=epsilon):
numberSqureRoot=numberSqureRoot-(((numberSqureRoot**2) - k)/(2*numberSqureRoot))
print("squre root of %s is %s " %(numberTarget,numberSqureRoot))
以上关于Python穷举指定长度密码的示例及算法对比即为全部内容,希望能提供有益参考,感谢支持。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









