我的目标是找到字符串中的重复字符,用其他值替换那些唯一和非唯一的元素,并将这些其他值放在另一个字符串中。你知道吗
我用了Counter
,但到目前为止我得到的是:
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")
输出:
'((((()'
例如,对于"binaryy"
,输出应该是'((((())'
,而不是'((((()'
。你知道吗
另外,有没有比print("'" + final_result + "'")
更好的打印字符串的方法
在您最初的方法中,当您执行
for key in dict_input:
操作时,您正在迭代计数器的键,因此您将最终创建一个等于计数器中键长度的字符串,正如您在输出中观察到的((((()
。你知道吗此外,字典仅来自Python3.6+,因此您无论如何都不能遍历键,这些键可以无序地重新创建原始字符串。你知道吗
相反,一旦创建了计数器,就需要遍历每个字符,并根据该字符的计数是1还是更大,将
(
或)
添加到字符串中同样对于带引号的打印,可以使用f字符串或字符串格式返回带引号的输出
输出将是
循环不应超过
for key in dict_input:
。这只适用于您的示例,因为A)字典是在python3.6+中排序的,B)您只有一个重复范围。循环应该对字符串中的实际字符进行编码:你可以(也许应该)缩短到
要打印带引号的字符串,只需使用
repr
。或者直接:或使用格式:
相关问题 更多 >
编程相关推荐