-2

I'm trying to do this exercise from Codewars:

The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate. Here is my code:

def duplicate_encode(word):
    new_word = ''
    for i in word:
        if word.count(i) == 1:
            new_word += '('
        else:
            new_word += ')'
    return new_word

When converting the word Success, I've got (())()) instead of )())()).

Could anyone please tell me how to solve it?

Lam Nguyen
  • 25
  • 4
  • 1
    A question title about your program's output in a way divorced from why it does/doesn't get that output is much less useful to others than a title that talks about the _specific technical problem_ you need to fix to get the correct output – Charles Duffy Aug 05 '21 at 13:49
  • 1
    Remember, the point of a Stack Overflow question is so others with the same problem can find and learn from the question's answers (we're here to build a knowledgebase, not to provide 1-on-1 help to individuals). The next person whose problem is caused by `S` being different from `s` probably won't know that that has anything to do with `(())())` being different from `)())())`, so this title doesn't help them find the question (and answers) that would help them solve their issue. – Charles Duffy Aug 05 '21 at 13:51

2 Answers2

2

You are not "ignoring capitalization":

def duplicate_encode(word):
    word = word.lower()  
    # as you were

Algorithmically, you should use a collections.Counter to collect all counts in a single iteration:

from collections import Counter

def duplicate_encode(word):
    word = word.lower()  
    counts = Counter(word)
    return "".join("(" if counts[x]==1 else ")" for x in word)
user2390182
  • 72,016
  • 6
  • 67
  • 89
1

"S" is not the same as "s". "HeLlo".count("l") for example returns 1 since it's case sensitive. You should add word = word.lower() above your for loop and it will work.

def duplicate_encode(word):
    word = word.lower()
    new_word = ''
    for i in word:
        if word.count(i) == 1:
            new_word += '('
        else:
            new_word += ')'
    return new_word

print(duplicate_encode("Success"))

Results in )())()).

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Jonathan1609
  • 1,809
  • 1
  • 5
  • 22