DEV Community

loading...

Discussion on: Daily Challenge #259 - Duplicate Encoder

Collapse
elcio profile image
Elcio Ferreira

A magical Python solution:

def encode(text):
    return ''.join((')' if text.lower().count(c.lower()) > 1 else '(' for c in text))

A boring Python solution:

def encode(text):
    encoded = ''
    for char in text:
        encoded += replace_char(char, text)
    return encoded

def replace_char(char, text):
    if text.lower().count(char.lower()) > 1:
        return ')' 
    return '('

Boring is good. I usually avoid oneliners and magical solutions.

A more "production ready" version of the above:

'''A "duplicate encoder"s.

Based on https://dev.to/thepracticaldev/daily-challenge-259-duplicate-encoder-2e8l

When running on command line, encodes standard input.

You can also use the following args:

-t : Executes automated testing
-h : Shows this help'''

def encode(text):
    '''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.
    Examples:
    >>> encode('Success')
    ')())())'
    >>> encode('(( @')
    '))(('
    >>> encode('din')
    '((('
    >>> encode('recede')
    '()()()'
    '''
    encoded = ''
    for char in text:
        encoded += replace_char(char, text)
    return encoded

def replace_char(char, text):
    '''Returns ')' if char appears more than once in text. Otherwise, 
    returns '('. Case insensitive. Examples:
    >>> replace_char('a', 'banana')
    ')'
    >>> replace_char('B', 'banana')
    '('
    '''
    if text.lower().count(char.lower()) > 1:
        return ')'
    return '('

if __name__ == '__main__':
    import sys
    if sys.argv[-1] == '-t':
        import doctest
        doctest.testmod()
    elif sys.argv[-1] == '-h':
        import pydoc
        print(pydoc.getdoc(sys.modules[__name__]))
    else:
        print(encode(sys.stdin.read()))