My code:
a = "dinaa"
newstr = ''
for char in set(a):
counts = a.count(char)
if counts > 1:
new = a.replace(char, ")")
else:
new = a.replace(char, '(')
print(new)
Output from above code:
di(aa
d(naa
din))
(inaa
Expected output:
((())
My question: Any tips how I should fix my code to get one output with all changed chars?
CodePudding user response:
like this ?
from collections import Counter
text = "dinaa"
for letter, count in Counter(text).items():
if count > 1:
text = text.replace(letter, ")")
else:
text = text.replace(letter, "(")
text # '((())'
CodePudding user response:
You are printing the intermediate result in each iteration, and then replacing that with a fresh copy of a
. Presumably you meant to replace in newstr
, not in a
?
a = "dinaa"
newstr = a
for char in set(a):
counts = a.count(char)
if counts > 1:
newstr = newstr.replace(char, ")")
else:
newstr = newstr.replace(char, '(')
print(newstr)