从python中的字符串中删除连续的重复字符 [英] Remove consecutive duplicate characters from a string in python
问题描述
嘿,我试图编写一个程序,该程序将从字符串中删除连续的重复字符.
Hey I was trying to write a program which will remove the consecutive duplicate characters from a string.
例如:
字符串-> aabbccde
第一次迭代:bbccde
第二次迭代:ccde
第三次迭代:de
for example:
string->aabbccde
first iteration: bbccde
second iteration: ccde
third Iteration: de
而德是答案.
以下是我编写的程序.
a = "aabbcs"
def remove_dups(st,ind):
print st, ind
st = st.replace(st[ind], "")
print st, "in dups"
find_dups(st)
def find_dups(text):
s=text
print s, "in find"
ln = len(s)
print ln
fg = 0
ind = 0
if ln==1:
print s, 'len'
return s
for i in range(0,ln-1):
if(s[i]==s[i+1]):
ind = i
remove_dups(s,ind)
print s, 'check'
return s
ans = find_dups(a)
print 'answer', ans
以下是我得到的输出
查找中的aabbcs
6
aabbcs 0
英国广播公司成对的
bbcs在find
4
bbcs 0
cs in dups
查找中的cs
2
cs check
bbcs检查
aabbcs 2
AAC APS
查找中的AAC
4
aacs 0
cs in dups
查找中的cs
2
cs check
AAC检查
aabbcs检查
回答aabbcs
aabbcs in find
6
aabbcs 0
bbcs in dups
bbcs in find
4
bbcs 0
cs in dups
cs in find
2
cs check
bbcs check
aabbcs 2
aacs in dups
aacs in find
4
aacs 0
cs in dups
cs in find
2
cs check
aacs check
aabbcs check
answer aabbcs
在上面,我们已经得到了cs,但是答案仍然是原始字符串,我可以理解这是由于递归,但是无法理解如何解决该问题.一点帮助将不胜感激.谢谢!
here above we have got cs but still answer is coming original string, I can understand it is because of recursion, but unable to understand how to resolve the issue. A little help would be appreciated. Thanks!
推荐答案
您的行remove_dups(s,ind)
是问题.它不对返回的值做任何事情.如果您仔细阅读了代码,则在顶层函数调用中,将在顶部分配s=text
,然后在底部返回s
,而无需修改s
的值.提示是,在打印正确答案后,您将最后打印原始文本.
尝试s = remove_dups(s, ind)
Your line remove_dups(s,ind)
is the problem. It's not doing anything with the returned value. If you read through your code, in the top level function call you're assigning s=text
at the top, then returning s
at the bottom, without ever modifying the value of s
. The clue is that you're printing the original text last, after you've printed the correct answer.
Try s = remove_dups(s, ind)
这篇关于从python中的字符串中删除连续的重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!