计算每个输入的错误密码存储的错误字符数

2024-03-29 06:27:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我写的剧本如下:

numString = []
count = 0
while(True):
    numInput=raw_input("Please enter your password\n")
    count = count + 1
    if numInput!="rusty":
        numString.append(numInput)

    else:
        break

def write_textfile(filename):
    ofile = open('wrongpasswords.txt','w')  
    ofile.write("\nIncorrect password 1:" +  numString[0])
    ofile.write("\nIncorrect password 2:" +  numString[1])
    ofile.write("\nIncorrect password 3:" +  numString[2])
    ofile.write("\nCorrect password entered on " + str(count)+"th entry")
    ofile = open('wrongpasswords.txt', 'r')
    for line in ofile:
            print line
    ofile.close()

ofile = open('wrongpasswords.txt', 'r')   
write_textfile(ofile)

打印以下内容

Incorrect password 1: rusty123
Incorrect password 2: Rusty
Incorrect password 3: rustless
Correct password entered on 4th entry.

我想写一个可以打印以下内容:

Incorrect password 1: rusty123 , wrong by 3 characters.
Incorrect password 2: Rusty , wrong by 1 characters.
Incorrect password 3: rustless , wrong by 4 characters.
Correct password entered on 4th entry.

我试过使用difflib。你知道吗


Tags: txtoncountpasswordopenwriteentrywrong
1条回答
网友
1楼 · 发布于 2024-03-29 06:27:47

你需要的是Hamming distance。你知道吗

def Hamming(a, b):
    K=len(a)

    # Hamming distance is only for pieces of data
    # that are of equal length
    if K!=len(b):
        return -1

    cnt=0
    for x in range(K):
        if a[x]!=b[x]: cnt+=1

    # if the strings are equal, returns zero,
    # number of non-equal characters otherwise
    return cnt

在代码中这样使用它:

correct="rusty"

ofile.write("\nIncorrect password 1: {}, {} characters are incorrect".format(numString[0], Hamming(numString[0], correct)))

相关问题 更多 >