检查需要删除多少个字符才能在Python中制作字谜
我写了 python 代码来检查需要从两个字符串中删除多少个字符才能使它们成为彼此的字谜。
这是问题陈述“给定两个字符串,并且 ,它们的长度可能相同,也可能不同,请确定制作和字谜所需的最少字符删除次数。可以从任何一个字符串中删除任何字符”
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.
该|合并两个结果计数器。然后我们取 this 的值,并将它们相加以获得在任一字符串中过度表示的字符总数。这相当于需要删除以形成字谜的最小字符数。
至于为什么你的代码不起作用,我无法确定任何一个问题。为了获得下面的代码,我所做的只是一些简化(例如删除不必要的变量,将 a 和 b 一起循环,删除== Trueand == False,替换t为 a set,给出变量描述性名称等),然后代码开始工作。这是简化的工作代码:
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
我建议您重点学习如何编写简单/短代码。与实际处理算法和获得结果相比,这似乎并不重要。这看起来像是清理或造型工作。但它的回报是巨大的。简单的代码更难引入错误,也更容易发现。通常,简单的代码也比等效的复杂代码的性能更高,要么是因为程序员能够更容易地看到改进它的方法,要么是因为更高性能的方法只是从更清晰的代码中自然产生的。