2016-09-28 5 views
1

문자열을 한 번만 표시되는 각 문자가 새 문자열에 '('으로 나타나는 word 문자열로 변환해야합니다. 원래 문자열의 중복 문자는 ')'으로 바꿔야합니다.중복 문자열 문자 대체

아래에 내 코드 ...

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

다음과 같이 내가 전달하고 있지 않다 테스트는 다음과 같습니다

'(((((('동일해야한다 '()()() 당신의 결과는 단어 문자의 발생 수를 기반으로 같은

예를 들어, 입력이 "물러나,"경우이 출력이 ()()()을 읽어야을 제안합니다.

+0

경우 ((((((('('()()로 바뀌어야한다), 당신이해야 할 일은 각 문자를위한 것이다. 그것을 뒤로 물러나는 경우에는 ')'로 바뀌어야한다. 'Recede'는 대부분의 영어 단어와 마찬가지로 변경되지 않습니다. –

답변

0

보인다 해당 추적 할 Counter를 사용할 수 있습니다

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') 
# '()()()' 
+0

이것은 매우 유용합니다! 나는 나의 기능이 또한 케이스를 무시하고 싶다는 것을 언급하는 것을 잊었다. 그래서 "성공"을 취하십시오 - 돌아와야합니다)())()). –

+0

'.lower()'메소드를 사용하여 단어를 소문자로 변환 할 수 있습니다. 업데이트를 참조하십시오. – Psidom

+0

훌륭함, 완벽하게 작동했습니다! –

1

코드는 그냥 잘 될 몇 가지 변화가 필요 좋다.

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

난 당신이 대답을 :) 것 같아

1

그냥 (이 늦게 등)가 가능하기 때문에 : 테스트는 '그런 것입니다

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