Hi, I'm still a beginner and a bit lost. I'm working on a project for school that requires me to write different small programs that will 'guess' the given password. This is a bruteforce program, and I need it to guess every possible combination of 4 number passwords like those on the old iPhones. My problem is that when I use random.sample it generates the same random numbers multiple times. What function can I use, or what should I change so that the random numbers within the given range don't repeat themselves? I tried doing rand.int but it gave me "TypeError: 'int' object is not iterable"如何在python中的循環和範圍內生成隨機的非循環數字?
Additional questions: - How do I get my loop to stop once n == Password4 ? It simply continues, even after the correct password is found. - Is there a way I can count the number of fails(n != Password4) before my success (n == Password4)?
這是我的代碼:
import random
Password4 = 1234
def crack_password():
while True:
for n in (random.sample(range(1112, 10000), 1)):
while n == Password4:
print(n, "is the password")
break
if n != Password4:
print('fail')
break
crack_password()
更新:使用代碼現在不產生隨機的非經常性的數字,但適用於我預期目的。請仍然可以自由回答原始問題,並非常感謝您的好意和迅速回復。
新代碼(歸功於@roganjosh):
import datetime as dt
Password4 = 9999
def crack_password():
start = dt.datetime.now()
for n in range(10000):
password_guess = '{0:04d}'.format(n)
if password_guess == str(Password4):
end = dt.datetime.now()
print("Password found: {} in {}".format(password_guess, end - start))
break
guesses = crack_password()
您的代碼將總是重複:'循環 –
這是棘手的,因爲'int's不能有前導零。所以如果密碼是0000-0999,你不能把它作爲一個數字。像字符串一樣對待密碼,而不是數字。 –
如果您嘗試在一個範圍內使用隨機密碼,而不是按順序執行,會有什麼不同?如果您沒有跡象表明某項失敗的原因,請逐一從「0000」到「9999」。順便提一下,這也可以計算作爲副產品的故障次數。 – roganjosh