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

时间:2018-07-04 00:44:09

标签: python python-3.x

我正在尝试解决这个问题。我已经看到了其他涉及列表和使用递归的解决方案,但是我有兴趣学习如何使用循环来解决这个问题,我的问题是我无法打印出最后一个字符,因为它等于一个空变量。

input:abbabd
expected output:aabd

代码:

answer = input("enter a string: ")
new_answer = ""
p = ""
repeat = ""
len_answer = len(answer)
run = False

for c in answer:
    if c != p and run == False:
        new_answer += p
        p = c
        run = False

    elif c == p:
        p = c 
        run = True

    elif run == True and c != p:
        p = c 
        run = False 

    else: 
        new_answer += p


print(new_answer)

5 个答案:

答案 0 :(得分:2)

您需要修复的代码是添加一些在循环结束后运行的额外代码,并在必要时在结果的末尾添加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

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

答案 1 :(得分:1)

最简单的方法是:

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] )

答案 2 :(得分:1)

使用zip_longestitertools模块中的defaultdict的另一种方法:

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

答案 3 :(得分:1)

@Angel ,您还可以尝试以下代码从输入字符串const Users=mongoose.model('user',UserSchema); Users.updateOne({'tds.todos._id':'5b3bebb247737b77b2ecc397','tds.todos.todo':'something to do'},{'tds.todos.todo':'Lets do something'}).then((users)=>{ console.log(users); }); 中删除相邻重复项,并返回输出字符串answer

我在函数new_answer中组织了代码,以实现代码可重用性,并使用注释记录了大多数行。

  

http://rextester.com/YWWFZ33548在线试用代码

remove_adjacent_duplicates()

答案 4 :(得分:0)

为解决这个问题,我们使用堆栈并进行for循环。

时间复杂度为O(n)。

    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