3 回答
TA贡献1804条经验 获得超3个赞
另一个解决方案。从一组(唯一的)字符开始,遍历字符串中的字符,从该组中删除字符,如果它已经被删除,那么它必须是重复的。使用它来构建一组重复的字符。
def duplicate_encode(word):
word = word.upper()
s = set(word)
dups = set()
for char in word:
if char in s:
s.remove(char)
else:
dups.add(char)
return "".join(")" if char in dups else "("
for char in word)
print(duplicate_encode("'yy! R)!QvdG'"))
给出:
))))((()(((()
TA贡献1826条经验 获得超6个赞
from collections import Counter
def duplicate_encode(word):
res = list(word.lower())
counter = Counter(word.lower())
counter2 = dict.copy(counter)
print(counter2)
for k, value in enumerate(res):
if counter2[value] == 1:
res[k] = '('
else:
res[k] = ')'
# for key in counter2.keys():
# word = str(word.lower()).replace(key, str(counter2[key]))
return "".join(res)
res = duplicate_encode('yy! R)!QvdG')
print("res", res)
TA贡献1871条经验 获得超13个赞
(当您的输入字符串包含大括号(如or )时,就会出现问题)。
当发生这种情况时,就像在您的示例中一样,错误的字符将被替换,您可以通过print()在代码中添加语句来验证,每次更改时word。
我已经在你的代码中替换了那部分。
from collections import Counter
def duplicate_encode(word):
counter = Counter(word.lower())
counter2 = dict.copy(counter)
print(counter2)
for k,v in counter2.items():
if counter2[k]==1:
counter2[k]='('
else:
counter2[k]=')'
print(counter2)
new_word = ''
for character in word:
new_word += counter2[character.lower()]
return new_word
但是请注意,该代码有很多冗余和不必要的内存使用。它可以简化为以下内容:
from collections import Counter
def duplicate_encode(word):
lower_word = word.lower()
new_word = ''
counter = Counter(lower_word)
for char in lower_word:
if counter[char] > 1:
new_word += ')'
else:
new_word += '('
return new_word
添加回答
举报
