gpt4 book ai didi

python - 检查需要删除多少个字符才能在 Python 中生成字谜

转载 作者:行者123 更新时间:2023-12-02 16:10:59 27 4
gpt4 key购买 nike

我写了 python 代码来检查需要从两个字符串中删除多少个字符才能使它们成为彼此的变位词。

这是问题陈述“给定两个字符串, and ,长度可能相同,也可能不同,确定进行和变位词所需的最少字符删除数。可以从任一字符串中删除任何字符”

def makeAnagram(a, b):
# Write your code here
ac=0 # tocount the no of occurences of chracter in a
bc=0 # tocount the no of occurences of chracter in b
p=False #used to store result of whether an element is in that string
c=0 #count of characters to be deleted to make these two strings anagrams
t=[] # list of previously checked chracters

for x in a:
if x in t == True:
continue
ac=a.count(x)
t.insert(0,x)
for y in b:
p = x in b
if p==True:
bc=b.count(x)
if bc!=ac:
d=ac-bc
c=c+abs(d)

elif p==False:
c=c+1

return(c)

最佳答案

您可以使用 collections.Counter为此:

from collections import Counter

def makeAnagram(a, b):
return sum((Counter(a) - Counter(b) | Counter(b) - Counter(a)).values())

Counter(x)(其中 x 是一个字符串)返回一个字典,该字典将字符映射到它们在字符串中出现的次数。

Counter(a) - Counter(b) 为您提供了一个字典,将 b 中过多的字符映射到它们在 b< 中出现的次数 超过它们在 a 中出现的次数。

Counter(b) - Counter(a) 与上面类似,但对于 a 中过多的字符。

| 合并了两个生成的计数器。然后我们取这个值,并将它们相加得到在任一字符串中过多的字符总数。这相当于构成一个字谜需要删除的最少字符数。


至于为什么您的代码不起作用,我无法确定其中的任何一个问题。为了获得下面的代码,我所做的只是一些简化(例如删除不必要的变量,将 a 和 b 一起循环,删除 == True== False,替换 tset,给变量描述性名称等),代码开始运行。这是简化的工作代码:

def makeAnagram(a, b):
c = 0 # count of characters to be deleted to make these two strings anagrams
seen = set() # set of previously checked characters
for character in a + b:
if character not in seen:
seen.add(character)
c += abs(a.count(character) - b.count(character))
return c

我建议您着重学习如何编写简单/简短的代码。与实际处理算法并获得结果相比,这似乎并不重要。这看起来像是清理或造型工作。但它的返回是巨大的。错误更难在简单的代码中引入,但更容易发现。通常,简单的代码也比等效的复杂代码具有更高的性能,这要么是因为程序员能够更轻松地找到改进它的方法,要么是因为更简洁的代码自然而然地产生了更高性能的方法。

关于python - 检查需要删除多少个字符才能在 Python 中生成字谜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68043856/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com