【问题标题】:What am I doing wrong in this problem for encoding a string?在编码字符串的这个问题中我做错了什么?
【发布时间】:2021-09-27 20:47:31
【问题描述】:

我一直在尝试为 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(

我做错了什么?

【问题讨论】:

  • 您有两个print() 语句。
  • 是的,那是我的错。我在这里发帖时忘记编辑它。我编写了print(c) 语句,以便我可以跟踪为更大的字符串返回的值。

标签: python string for-loop replace encoding


【解决方案1】:

您还需要更新原始字符串。如果你不这样做,你只是用新的值写了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)

【讨论】:

  • 第二种方法也会在 a="b(" 我相信时给出正确的结果。应该是 "((" 我相信,但很确定方法 1 会给出 "))"
【解决方案2】:

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

from collections import Counter

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2020-11-16
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多