Mr. Jibz
Mr. Jibz

Reputation: 521

Replace Duplicate String Characters

I need to convert a string word where each character that appears only once should be appear as '(' in the new string. Any duplicate characters in the original string should be replaced with ')'.

My code below...

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

The test I'm not passing is as follows:

'((((((' should equal '()()()'

This would suggest that, if for example, the input is "recede," the output should read ()()().

Upvotes: 1

Views: 2183

Answers (3)

cdlane
cdlane

Reputation: 41862

Just because (it's late and) it's possible:

def duplicate_encode(word):

    return (lambda w: ''.join(('(', ')')[c in w[:i] + w[i+1:]] for i, c in enumerate(w)))(word.lower())

print(duplicate_encode("rEcede"))

OUTPUT

> python3 test.py
()()()
>

Upvotes: 1

Arun V Jose
Arun V Jose

Reputation: 3379

Your Code is Good just need some alteration it will be great.

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")

I think you got the answer :)

Upvotes: 1

akuiper
akuiper

Reputation: 214927

Seems like your result is based on the number of occurrences of a character in the word, you can use Counter to keep track of that:

def duplicate_encode(word):
    from collections import Counter

    word = word.lower()              # to disregard case
    counter = Counter(word)
    new_word = ''
    for char in word:
        if counter[char] > 1:        # if the character appears more than once in the word 
                                     # translate it to )
            new_word += ')'
        else:
            new_word += '('
    return new_word

duplicate_encode('recede')
# '()()()'

Upvotes: 0

Related Questions