Python:随机4位密码猜测,可以';我想不出一个问题
我是Python新手。我有一个程序,让你猜一个随机的4位密码。例如,如果密码是Python:随机4位密码猜测,可以';我想不出一个问题,python,passwords,Python,Passwords,我是Python新手。我有一个程序,让你猜一个随机的4位密码。例如,如果密码是5530,如果我猜里面有一个5(例如5111),它说我猜对了2个数字。如果密码是5535,它说我猜对了3个数字 但实际上,它解释了我答案中的单个5,对于其他5s是正确的。我只想说,如果有两个或三个5s,我就猜对了一个数字;如果我为5530键入了两个5s,我就猜对了两个;如果我为5535键入了三个5s,我就猜对了三个 import random no1 = random.randint(0, 9) no2 = rand
5530
,如果我猜里面有一个5
(例如5111
),它说我猜对了2个数字。如果密码是5535
,它说我猜对了3个数字
但实际上,它解释了我答案中的单个5
,对于其他5
s是正确的。我只想说,如果有两个或三个5
s,我就猜对了一个数字;如果我为5530
键入了两个5
s,我就猜对了两个;如果我为5535
键入了三个5
s,我就猜对了三个
import random
no1 = random.randint(0, 9)
no2 = random.randint(0, 9)
no3 = random.randint(0, 9)
no4 = random.randint(0, 9)
password = str(no1) + str(no2) + str(no3) + str(no4)
count = 0
if no1 % 2 == 0:
count += 1
if no2 % 2 == 0:
count += 1
if no3 % 2 == 0:
count += 1
if no4 % 2 == 0:
count += 1
print(password)
print(f"Hint: The password consists of {count} even number(s)")
guess = input("Guess the 4 numbers: ")
present = 0
if str(no1) in guess:
present += 1
if str(no2) in guess:
present += 1
if str(no3) in guess:
present += 1
if str(no4) in guess:
present += 1
if present == 4:
if guess == password:
print("Congrats! You have guessed the password correctly.")
else:
print("All the numbers are present but not in the correct sequence.")
print(f"You did not make it! The password is {password}.")
else:
print(f"{present} number(s) of your guess are present in the password.")
print(f"You did not make it! The password is {password}.")
p.S.我希望我下面的代码可能会因为范围等内容而缩短,但我没有信心这样做,所以有人能帮我解决这个问题吗?改变这个:
if str(no1) in guess:
present += 1
if str(no2) in guess:
present += 1
if str(no3) in guess:
present += 1
if str(no4) in guess:
present += 1
致:
另一种方式:
rand_nums = [no1, no2, no3, no4]
for i in range(4)
if (int(guess[i]) == rand_nums[i]):
present += 1
您必须将密码中的每个数字与guess中的每个数字进行比较。为此,您必须使用索引访问guess。像这样:
if str(no1) in guess[0]:
present += 1
谢谢你的回答,它比我现在的好,但我希望它能工作,即使它的顺序不对,可能吗?如果我使用答案中的代码,我无法获得密码顺序不正确的输出。例如,如果密码是5530,我使用你们提供的答案和guess 1155,我的猜测中有0个数字出现在密码中,但我想说密码中有2个数字出现在我的猜测中。谢谢,但如果我使用答案中的代码,我无法获得密码顺序不正确的输出。例如,如果密码是5530,我使用你们提供的答案和guess 1155,我得到密码中有0个我的猜测数字,但我想说密码中有2个我的猜测数字。好吧,你可以创建一个新变量,例如,勾号。使其等于零,并使用它来查看密码和猜测是否匹配。另一方面,以您最初使用的方式使用present,最后做出if/else语句,通过勾选“tick”检查密码是否正确,并通过勾选“present”检查密码是否存在。基本上,使用答案中的代码加上“tick”,然后在下面添加您最初使用的代码。也许有一种更经济的方法可以做到这一切,但我目前还不太熟悉语法,所以我无法在我的IDE中轻松地检查它。虽然有点让人困惑,但我会尝试使用thankscount=len([num for num in str(password)if int(num)%2==0])present=len([num for num in str(password)if str(num)in str in str(guess)])
if str(no1) in guess[0]:
present += 1