在这个字符串编码问题中,我做错了什么



我一直在尝试为一个codewars问题/kata编写这个程序,该问题读取一个字符串,并将该字符串转换为一个新字符串,其中新字符串中的每个字符都是"("如果该字符在原始字符串中只出现一次,或"(";如果该字符在原始字符串中出现多次。在确定字符是否重复时忽略大写。

所以,下面是我写的小代码,然后开始处理问题的更大部分:

a = "Eren"
b = a.lower()
for i in b:
c = b.count(i)
print(c)
if c == 1:
d = b.replace(i, "(")
else:
d = b.replace(i, ")")
print(d)

我原以为输出是

)()(

但我得到的是

ere(

我做错了什么?

您还需要更新原始字符串。如果你不这样做,你只是用新的值重写了d的前一个值。由于b没有变化,所以您得到了ere(。相反,做

a = "Eren"
b = a.lower()
for i in b:
c = b.count(i)
print(c)
if c == 1:
d = b.replace(i, "(")
b=b.replace(i, "(")  #==== Replace the original string too
else:
d = b.replace(i, ")")
b=b.replace(i, ")") #==== Replace the original string too
print(d)

您的输出看起来像:

)()(

但是,在对b值进行迭代时更改它似乎不是一个好主意

a = "Eren"
b = a.lower()
d=''
for i in b:
c = b.count(i)
print(c)
if c == 1:
d += '('
else:
d+=')'
print(d)

我可以建议一个不同的(更高效的(实现吗?

from collections import Counter
count = Counter(a.lower())
b = ''.join('(' if count[c] == 1 else ')' for c in a.lower())

这里的重点是,你不想把每个字符都数一次以上。例如,假设您有一个字符串"eeeeee"。你不需要数六次。这就是为什么你应该使用collections.Counter

相关内容

最新更新