【发布时间】:2021-03-02 16:07:14
【问题描述】:
我正在为计算机安全课程编写的一段代码苦苦挣扎。
我正在尝试编写一段测试代码,根据解决时间来测试 4 位密码。
我想从 4 个全 0 的数字开始。对于每个数字,测试从 0 到 9 的数字。
如果我从大于 0.2 秒的函数中得到响应,则使用该数字更改 pw 列表,然后移至下一个。
但是我的代码没有在列表中递增。 我尝试在 if 语句之后简单地插入一个 break,但意识到我还必须打破我们的外部“for 循环”,我尝试在这里插入一个 break,但仍然无法让我的代码工作。
我错过了什么?
import time
import sys # ignore
sys.path.insert(0,'.') # ignore
real_password = '2234'
#This function cannot be changed
def check_password(password): # Don't change it
if len(password) != len(real_password):
return False
for x, y in zip(password, real_password):
time.sleep(0.1) # Simulates the wait time of the safe's mechanism
if int(x) != int(y):
return False
return True
def crack_password():
pw = [0,0,0,0]
cnt = 0
if cnt < 3:
for i in range (0,9):
pw[cnt] = i
start = time.time()
check_password(create_string(pw))
stop = time.time()
t_time = stop - start
print(pw[cnt], t_time)
#Struggling with my code here!
#Creates a string from the list
def create_string(pw_list):
string = ''
for char in pw_list:
string += str(char)
return string
我在crack_password函数中的打印语句提供:
0 0.10016393661499023
1 0.10017132759094238
2 0.1006174087524414
3 0.10022568702697754
4 0.1002652645111084
5 0.20053935050964355
6 0.10025167465209961
7 0.10107183456420898
8 0.10021018981933594
因此我知道密码的第一个数字是 5,因为它大于 0.2。然后我怎样才能打破这个循环并移动到 pw 整数的下一次迭代?
【问题讨论】:
-
这能回答你的问题吗? How to break out of multiple loops?
-
我之前读过这篇文章,但它并没有真正帮助我,我认为我正在为我的实施而苦苦挣扎。
-
所以我意识到不是循环破坏了我的代码,而是我的 if 语句时机。所以跳出循环的链接是正确的。