比较两个字符串并将差异保存为 Python 中的整数

Compare two strings and save the difference as an integer in Python

如果我有密码 "rusty",我输入序列:"rusty123"、"Rusty" 和 "rush"(依次保存到列表 newList ), 当我打印出 newList 时,我如何显示这样的结果:

rusty123, wrong by 3 characters

Rusty, wrong by 1 characters

rush, wrong by 2 characters

?

我需要添加的是一个类似于 (countDifference) 的函数,它允许我将正确的密码 'rusty' 与输入的错误密码进行比较。因此,如果我输入 'rusty123',它应该将 'rusty' 与 'rusty123' 进行比较并将结果保存为整数(3 - 因为密码相差 3 个字符,即 123 是错误的)。然后我将这个整数转换为字符串并将其记录到文件 newFile.

我认为将 (password ='rusty') 作为常量,然后读取新密码输入的每一行并进行比较,这样 'rusty' 就可以了,但我只是不知道如何。

password = "rusty"

user_input = raw_input("Please enter the password")

所以用户输入:"Rusty" 函数读取密码错误1个字符,即"R" - (应该是小写的)

已解决:如果您遇到同样的问题,请按照@Chris Beck 在其解释末尾提供的 link 进行操作。完美的解决了这个问题。

Is there a function that can help me determine by how many characters (in integers) the wrong password (entered as a string) was from the right password?

所以,这可能意味着一些不同的事情。人们使用的 "by how many characters does this string differ from that string" 有几种不同的概念。其中一些比其他的更容易编程,如果您是新手,那么您可能不想使用最复杂的版本。

"Distance" 从字符串 A 到字符串 B

最简单:

At how many indices i does A[i] != B[i]? (If one string is longer than the other then count all those indices as mismatching also.)

这是最容易实现的一个。然而,它并不总能给出最直观的结果。如果我有

A = "abracadabra"
B = "abrarcadabra"

这些字符串的距离将为 8,即使它们仅关闭 "by one letter"。

更难:编辑距离

在编辑距离下,上面的AB的距离为1。编辑距离是指,将A变为[需要执行多少次插入/删除=12=]。在某些变体下,两个相邻字符的交换也被认为只算作距离 1。

计算编辑距离的常用方法是使用动态规划。你可以在这里看到这样的例子:Edit Distance in Python