为了账号安全,请及时绑定邮箱和手机立即绑定

如何转义括号python

如何转义括号python

呼唤远方 2023-03-16 09:45:53
我是编程的新手。本练习的目标是将字符串转换为新字符串,其中新字符串中的每个字符为“(”(如果该字符在原始字符串中仅出现一次)或“)”(如果该字符在原始字符串中出现多次)细绳。在确定字符是否重复时忽略大写。但是当代码遇到 ) -- 右括号时,它会产生错误的输出。正如我发现的那样,问题出在正则表达式上,但我不知道如何修复代码。from collections import Counterdef duplicate_encode(word):    counter = Counter(word.lower())    counter2 = dict.copy(counter)    print(counter2)    for k,v in counter2.items():        if counter2[k]==1:            counter2[k]='('        else:            counter2[k]=')'      for key in counter2.keys():        word = str(word.lower()).replace(key, str(counter2[key]))         return word例如:duplicate_encode('yy! R)!QvdG')应该回来)))((()((((但我得到了(((((((((((。
查看完整描述

3 回答

?
狐的传说

TA贡献1804条经验 获得超3个赞

另一个解决方案。从一组(唯一的)字符开始,遍历字符串中的字符,从该组中删除字符,如果它已经被删除,那么它必须是重复的。使用它来构建一组重复的字符。


def duplicate_encode(word):

    word = word.upper()

    s = set(word)

    dups = set()


    for char in word:

        if char in s:

            s.remove(char)

        else:

            dups.add(char)


    return "".join(")" if char in dups else "("

                   for char in word)


print(duplicate_encode("'yy! R)!QvdG'"))

给出:


))))((()(((()


查看完整回答
反对 回复 2023-03-16
?
跃然一笑

TA贡献1826条经验 获得超6个赞

from collections import Counter



def duplicate_encode(word):

    res = list(word.lower())

    counter = Counter(word.lower())

    counter2 = dict.copy(counter)


    print(counter2)


    for k, value in enumerate(res):

        if counter2[value] == 1:

            res[k] = '('

        else:

            res[k] = ')'


    # for key in counter2.keys():

    #     word = str(word.lower()).replace(key, str(counter2[key]))


    return "".join(res)



res = duplicate_encode('yy! R)!QvdG')

print("res", res)


查看完整回答
反对 回复 2023-03-16
?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

(当您的输入字符串包含大括号(如or )时,就会出现问题)。

当发生这种情况时,就像在您的示例中一样,错误的字符将被替换,您可以通过print()在代码中添加语句来验证,每次更改时word。

我已经在你的代码中替换了那部分。


from collections import Counter


def duplicate_encode(word):

    counter = Counter(word.lower())

    counter2 = dict.copy(counter)


    print(counter2)


    for k,v in counter2.items():

        if counter2[k]==1:

            counter2[k]='('

        else:

            counter2[k]=')'

    

    print(counter2)

    

    new_word = ''

    for character in word:

        new_word += counter2[character.lower()]

    

    return new_word

但是请注意,该代码有很多冗余和不必要的内存使用。它可以简化为以下内容:


from collections import Counter


def duplicate_encode(word):

    lower_word = word.lower()

    new_word = ''

    counter = Counter(lower_word)

    

    for char in lower_word:

        if counter[char] > 1:

            new_word += ')'

        else:

            new_word += '('

    

    return new_word


查看完整回答
反对 回复 2023-03-16
  • 3 回答
  • 0 关注
  • 264 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号