Python - 比较“正确”排序的单词数量的最有效方法跨两个字符串/列表排序

发布于 2024-09-28 19:20:12 字数 219 浏览 0 评论 0原文

我想知道解决这个问题的计算效率最高的 Python 方法是什么。

假设您有两个字符串(或拆分这些字符串的列表 - 无关紧要),“这是正确的字符串”与“这是正确的字符串”。

我们假设第一个字符串总是正确的,并且将根据单词以正确的顺序排序来为第二个字符串分配分数。对于上面的两个字符串,我们将分配 0.6 的分数(因为 5 个单词中只有 3 个位于正确的位置)。

最好的, 乔治娜

I was wondering what the most computationally efficient Python way of cracking this problem would be.

Say you have two strings (or lists from splitting those strings--doesn't matter), "this is the right string" vs. "this is right the string."

We're assuming that the first string is always right, and a score will be assigned to the second string based on which words were sequenced in the right order. For the above two strings, we would assign a score of 0.6 (as only 3 of the 5 words are in the right position).

Best,
Georgina

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

终遇你 2024-10-05 19:20:12

这听起来很像家庭作业。尝试思考一下。遍历正确单词列表一次,并检查第二个列表中的相应单词是否等于正确列表中的单词是否就足够了?

我可能会在 python 中压缩列表并比较这些列表是否相等。

This sounds very much like homework. Try thinking about it for a bit. Would it suffice to traverse the list of correct words once, and check if the corresponding word in the second list is equal to the word in the correct list?

I would probably zip the lists in python and compare the pairs for equality.

浅忆流年 2024-10-05 19:20:12
a = "this is the right string"
b = "this is right the string"

sum([1 for i,v in zip(a.split(), b.split()) if i == v])
a = "this is the right string"
b = "this is right the string"

sum([1 for i,v in zip(a.split(), b.split()) if i == v])
逆光飞翔i 2024-10-05 19:20:12
sum(f == s for f, s in zip(first, second)) / len(first)
sum(f == s for f, s in zip(first, second)) / len(first)
请止步禁区 2024-10-05 19:20:12

使用 ord() 将每个字符转换为整数值(其序数值),然后使用按位运算符 ^ 将每个字符异或在一起。如果字符相同,异或运算将返回0(零),然后使用|=将返回值与结果按位或然后将操作结果保存为result。如果迭代所有字符后 result 仍然为零,则字符串是等效的。

a = "this is the right string"
b = "this is right the string"

result = 0
for x,y in zip(a,b):
    result |= ord(x) ^ ord(b)

(if result == 0): print "Equivalent"

Use ord() to convert each character to an integer value (its ordinal value), and then XOR each character together using the bitwise operator ^. If the characters are the same, the XOR operation will return 0 (zero), then use |= to bitwise OR the returned value with result and then save the result of the operation as result. If result is still zero after you iterate over all the characters, then the strings are equivalent.

a = "this is the right string"
b = "this is right the string"

result = 0
for x,y in zip(a,b):
    result |= ord(x) ^ ord(b)

(if result == 0): print "Equivalent"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文