1

My goal is to get to find the duplicate characters in a string and to replace those unique and non unique elements with other values and put those other values in another string.

I used a Counter, but this is what I got so far:

from collections import Counter

def duplicate_encode(word):
    word = word
    final_result = ""
    dict_input = Counter(word)
    print(dict_input)
    print(dict_input.items())
    for key in dict_input:
        x = int(dict_input[key])
        print("this is key" + "\t" + key)
        print(x)
        if x == 1:
            final_result += "("
        elif x != 1:
            final_result += ")"
    print("'" + final_result + "'")

duplicate_encode("binaryy")

Output:

'((((()'

For example for "binaryy" the output should be '((((())', not '((((()'.

Also, is there a better way to print a string than doing print("'" + final_result + "'")

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
matar770
  • 11
  • 1

2 Answers2

1

In your original approach, you are iterating over the keys of the counter when you do for key in dict_input:, hence you will end up create a string equal to the length of keys in the counter, which is ((((() as you observed in the output.

Also dictionaries are insertion-ordered only from Python3.6+, so you anyways cannot iterate over the keys which can be unordered to recreate your original string.

Instead once you create your counter, you need to iterate over each character, and add ( or ) to the string based on whether the character had count 1 or greater

Also for printing with quotes, you can either use f-strings, or string formatting to return the output with quotes around it

from collections import Counter

def duplicate_encode(word):

    counter = Counter(word)

    #Add ( if the count of character is 1, else add )
    output = ''.join('(' if counter.get(c) == 1 else ')' for c in word)

    #Return a f-string with single quotes around it
    return f"'{output}'"

    #Or use string formatting
    #return "'{}'".format(output)

print(duplicate_encode("binaryy"))

The output will be

'((((())'
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
1

Your loop should not be over for key in dict_input:. This only works in your example by pure luck because A) dictionaries are ordered in Python 3.6+, and B) you only have one range of duplicates. The loop should encode the actual characters in the string:

final_result = ''
for c in word:
    final_result += '(' if dict_input[c] == 1 else ')'

You can (and probably should) shorten this to

final_result = ''.join('(' if dict_input[c] == 1 else ')' for c in word)

To print the string with quotes around it, just use repr. Either directly:

print(repr(final_result))

or using formatting:

print(f'{final_result!r}')
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264