亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何轉義括號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 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號