如何检查 Python 中两个随机生成的字符串是否匹配

How to check if two randomly-generated strings match in Python

因为我正在尝试编写一个简单的脚本来检查使用“选择”函数生成的两个字符串是否匹配。 “选择”功能从给定列表中挑选字母。我在 while 循环中遇到问题。这是我的尝试:

from random import choice

list1 = ['a', 'r', 'l', 'd', 'n', 'm']

ticket = ''
for i in range(3):
    ticket += choice(list1)
print(f"This is the winning ticket: {ticket}\n")

my_tickets = []  #store here the tickets that don't match 
my_ticket = ''

for i in range(3):
    my_ticket += choice(list1)
print(f"The ticket you buy is: {my_ticket}")

active = True
while active:
    for i in range(3):
        my_ticket += choice(list1)

    if my_ticket == ticket:
        active = False
        print("Congratulations, you got the winning ticket!!")

    else:
        print('Try again')

你能帮我找出错误在哪里吗?是否可以在不使用字符串模块的情况下使这个脚本工作?谢谢

你没有描述出什么问题,但我建议在 else 语句中将 my_ticket 的值设置回 '' 并附加到 my_tickets 变量,因为评论建议,但你最终没有这样做。

您忘记在 while 循环中打印新抽取的彩票。如果不打印,您会错过您的门票变得越来越长并且永远不会匹配。

您的代码也有很多重复,当您一次可以使用 random.choices() 随机绘制 3 个字母时,您在循环中手动绘制了 3 个字母。

修正代码:

from random import choices
 
# avoid code duplication - simply use a function to provide a random ticket
# of specific length instead of repeating the code creating one ticket:
# DRY : dont repeat yourself
def get_ticket():
    letters = []
    return ''.join(choices('arldnm',k=3))

# get winner ticket
winner = get_ticket()
print(f"This is the winning ticket: {winner}\n")

my_tickets = []  # stores tickets that don't match

# loop until matching ticket found 
while True:
    my_ticket = get_ticket() 
    # you forgot to print your newly draftet ticket
    print(f"The ticket you buy is: {my_ticket}")
   
    if my_ticket == winner:
        print("Congratulations, you got the winning ticket!!")
        break
    else:
        # my_tickets.append(my_ticket) # you do nothing with it ...
        print('Try again')

输出:

This is the winning ticket: nad

The ticket you buy is: lnl
Try again
[... snipp 342 lines ...]
The ticket you buy is: ddd
Try again
The ticket you buy is: nad
Congratulations, you got the winning ticket!!