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

What am I doing wrong in this problem for encoding a string?

我一直在尝试为 codewars problem/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