Python 使用循环删除所有相邻的重复项

Python 使用循环删除所有相邻的重复项,python,python-3.x,Python,Python 3.x,我正在努力解决这个问题。我见过其他涉及列表和使用递归的解决方案,但我感兴趣的是学习如何使用循环解决这个问题,我的问题是我无法打印最后一个字符,因为它等于一个空变量 input:abbabd expected output:aabd 代码: 修复代码所需的只是添加一些在循环结束后运行的额外代码,并在必要时将p添加到结果末尾: if not run: new_answer += p 但是,如果结合一些条件,您可以稍微简化您的循环。它可以非常简单: for c in answer:

我正在努力解决这个问题。我见过其他涉及列表和使用递归的解决方案,但我感兴趣的是学习如何使用循环解决这个问题,我的问题是我无法打印最后一个字符,因为它等于一个空变量

input:abbabd
expected output:aabd

代码:


修复代码所需的只是添加一些在循环结束后运行的额外代码,并在必要时将
p
添加到结果末尾:

if not run:
    new_answer += p
但是,如果结合一些条件,您可以稍微简化您的循环。它可以非常简单:

for c in answer:
    if c == p:
        loop = True          # no need for p = c in this case, they're already equal
    else:
        if not loop:
            new_answer += p
        loop = False
        p = c

在此版本的循环之后,您仍然需要第一个代码块中的行。

最简单的方法是:

result = [[data[0], 1]]
for a in data[1:] :
    if a == result[-1][0] :
        result[-1][1] += 1
    else :
        result.append( [a,1] )

result = ''.join( [i[0] for i in result if i[1] == 1] )

使用
itertools
defaultdict
模块中的
zip\u longest
的另一种方法:

from itertools import zip_longest
from collections import defaultdict

def remove_dup(iterable):
    # seen[0] will be for non adjacent duplicates
    # the other indexes will be used in comparisons                 
    seen = defaultdict(list)
    seen[0], index = [''], 1
    for k, v in zip_longest(iterable, iterable[1:]):
        if not seen[index]:
            seen[index] = ['']
        # Here we compare with the last element of seen[index]
        # in order to escape multiples successive adjacent chars
        if k != v and k != seen[0][-1] and k != seen[index][-1]:
            # adding index to escape the scenario
            # where the last char of the previous index
            # is the same as the actual index
            index += 1
            seen[0] += [k]
        else:
            # add chars for further comparison in another index
            seen[index] += [k]

    return ''.join(seen[0])


# test:
tests = ['abbabd', 'aaabbbcdddeeefghkkkm', 'abbdddckkfghhhree', 'xaabx']
for test in tests:
    print('{} => {}'.format(test, remove_dup(test)))
输出:

abbabd => abd
aaabbbcdddeeefghkkkm => cfghm
abbdddckkfghhhree => acfgr
xaabx => xbx

@angle,您也可以尝试下面的代码从输入字符串
应答
中删除相邻的重复项,并返回输出字符串
新应答

我将代码组织在一个函数
remove_相邻的重复项()

请在以下位置联机尝试代码:


为了解决这个问题,我们使用了堆栈和for循环

这个问题的时间复杂度是O(n)


itertools.groupby()@AChampion
r=[];对于itertools.groupby('abbad')中的k,v:如果len(list(v))==1:r.append(k)
:),但如果不是在运行中,您可以在循环末尾添加
c
,例如,
如果不运行:new_answer+=c
,它应该会给出您的答案。使用while循环重新循环整个过程并取出所有重复的相邻副本有何建议@但是这个解决方案仍然缺少最后的章程。示例xaabx程序将只返回一个xb,而不是剩余的XY。你是说我的第二个代码块?它仍然需要在最后添加第一个代码块(在循环之外)。使用while循环重新循环整个过程并删除所有重复的相邻重复项有什么建议吗?我认为您认为第一项总是在输出中的假设是不正确的。如果我正确理解了问题,字符串
aaab
应该变成
b
(你应该去掉任何一行出现多次的字符)。您可以在输出中得到一行中的重复项,但前提是它们在原始输入中不相邻。@Blckknght right!我做了标准的
uniq()
,没有仔细阅读问题=)请稍等片刻,等待更好的解决方案。。。
abbabd => abd
aaabbbcdddeeefghkkkm => cfghm
abbdddckkfghhhree => acfgr
xaabx => xbx
def remove_adjacent_duplicates(answer):
    new_answer = ""    # output string
    ch_last = ""       # current character of last iteration
    start, end = 0, 0  # start and end indices of adjacent characters sequence

    for index, ch in enumerate(answer):
        if index: # for index 1 and onwards
            if ch == ch_last:
                end = index 
            else: # if new character encountered after repetition of any character
                if start == end: # if there is a repetition
                    new_answer = new_answer + ch_last
                start, end = index, index
        else:   # index == 0 (only 1st time)
            start, end = index, index

        ch_last = ch # save the current character to use it in next iteration

    if start == end: # if the last encountered character is not of repeating nature
        new_answer = new_answer + ch_last

    return new_answer

# START
if __name__ == "__main__":
    # INPUT 1
    answer = input("Enter a string: ")         # abbabd
    print(remove_adjacent_duplicates(answer))  # aabd

    # INPUT 2
    answer = input("Enter a string: ")         # abcddddeefffghii
    print(remove_adjacent_duplicates(answer))  # abcgh

    # INPUT 3
    answer = input("Enter a string: ")         # abcddddeefffghi
    print(remove_adjacent_duplicates(answer))  # abcghi    

    # INPUT 4
    answer = input("Enter a string: ")         # aa**mmmxxnnnnRaaI++SH((IKES))H
    print(remove_adjacent_duplicates(answer))  # RISHIKESH
    public class RemoveAdjacentDuplicates {

        public static void main(String[] args) {
            System.out.println(removeDuplicates("abbabd"));
        }

         public static String removeDuplicates(String S) {
             char[] stack = new char[S.length()];

             int i = 0;

             for(int j = 0 ; j < S.length() ; j++) {

                 char currentChar = S.charAt(j);
                 if(i > 0 && stack[i-1] == currentChar) {
                     i--;
                 }else {
                     stack[i] = currentChar;
                     i++;
                 }

             }
             return new String(stack , 0 , i);
         }

    }
    input:abbabd
    output:aabd