我需要转换字符串word,其中仅出现一次的每个字符应在新字符串中显示为'('。原始字符串中任何重复的字符都应替换为')'

我的下面的代码...

def duplicate_encode(word):
new_word = ''
for char in word:
    if len(char) > 1:
        new_word += ')'
    else:
        new_word += '('
return new_word


我没有通过的测试如下:

'((((((('应该等于'()()()'

这将表明,例如,如果输入为“ recede”,则输出应为()()()

最佳答案

您的代码是好的,只需要进行一些改动就可以了。

def duplicate_encode(word):
    """
    To replace the duplicate letter with ")" in a string.
    if given letter is unique it replaced with "("
    """
    word_dict = {}   # initialize a dictionary
    new_word = ""
    for i in set(word):   # this loop is used to count duplicate words
        word_count = word.count(i)
        word_dict[i] = word_count   # add letter and count of the letter to dictionary
    for i in word:
        if word_dict[i] > 1:
            new_word += ")"
        else:
            new_word += "("
    print new_word

duplicate_encode("recede")


我认为您已经找到答案了:)

10-04 22:34
查看更多