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

2024-05-23 16:06:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

Tags: andrunanswerfalsetrue列表newinput
3条回答

修复代码所需的只是添加一些在循环结束后运行的额外代码,并在必要时将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] )

@Angel,您也可以尝试下面的代码从输入字符串answer中删除相邻的重复项,并返回输出字符串new_answer。你知道吗

我在函数remove_adjacent_duplicates()中组织了代码,以实现代码重用性,并使用注释记录了大多数行。你知道吗

Try the code online at http://rextester.com/YWWFZ33548

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

相关问题 更多 >