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

时间:2016-01-18 13:05:49

标签: 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

1 个答案:

答案 0 :(得分:0)

您需要的是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)))