Python BruteForce HelloWorld

时间:2018-05-28 04:51:02

标签: python python-3.x

我正在尝试强力打印Hello World,我已经看过这个代码并尝试了它并且工作正常但是当我尝试使其动态时它不起作用。

import random
import sys
import time

targetArray = ["H",'e','l',"l","o"," ", "W", "o", "r","l","d" ]
stringArray = ["","","","","","","","","","",""]
i=0
count = 0
while i < len(targetArray):
    if stringArray[i] != targetArray[i]:
        stringArray[i] = chr(random.randint(0,256))

    if stringArray[i] == targetArray[i]:
        i += 1


    x = 0
    print("\n")
    while x< len(stringArray):
        print(stringArray[x]  , end = "" , flush = True)
        x += 1
        count += 1
    time.sleep(.01)

print("\nTotal Gusses is :",count)

但是当我尝试使用String时,它会无限地打印char。

import random
import sys
import time

targetString = "a"
string = []
i=0
x = 0
count = 0
print(len(targetString))
while string != targetString:
    for i in range(len(targetString)):
        string.append(chr(random.randint(32,126)))


    print("\n")
    while x< len(string):
        print(string[x]  , end = "")
        x += 1
        count += 1
    time.sleep(.01)

print("\nTotal Gusses is :",count)

如何让它动态化?

点数 - https://imgur.com/fNjhjUS

1 个答案:

答案 0 :(得分:2)

第一个问题是您只是初始化stringx 在循环之前。因此,它不断向string添加字符,以及 打印这些新角色,但string不断变长 更长,永远不会匹配targetString

第二个问题是targetString的类型为str,但string 属于list类型,因此它们当然永远不会相等。

第三个问题是我们不应该使用string作为标识符, 因为有一个名为string的标准库模块,这样就可以了 阴影那个名字。

不确定这是否是故意的,但在第一个程序中,你选择并且 一次匹配一个字符(线性时间),而在第二个匹配字符 程序,你一次选择和匹配所有这些(指数时间)。 实际上,甚至比指数还要差:如果targetString是长度N 并且您从M个字符(M = 95中选择给定代码), 复杂性为O(N * M ** N)

import random
#import sys    # not used
import time

targetString = list("a")
s = []
i = 0
x = 0
count = 0
print(len(targetString))
while s != targetString:
    s = []
    for i in range(len(targetString)):
        s.append(chr(random.randint(32,126)))
    print("")
    x = 0
    while x < len(s):
        print(s[x], end="")
        x += 1
        count += 1
    time.sleep(.01)

print("\nTotal Guesses is :",count)