python for while循环中的循环,但更好

2024-10-01 15:32:01 发布

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

我解决了一个python教程,但我肯定认为我的方法不是最好的

有人能推荐更好的while循环解决方案或其他解决方案吗

def solution(cryptogram):
    return decode(cryptogram)

def decode(str1):
    check = True
    list1 = list(str1)

    while check:
        check = False

        for i in range(len(list1)-1):

            if list1[i] == list1[i+1]:
                del list1[i+1]
                del list1[i]       
                check = True
                break
        
        if check == True:
            continue

        result = ''.join(list1)

        return result

print(solution('browoanoommnaon'))

这就是问题所在

喜欢密码的极客开发人员布朗这次使用了重复字符创建了一个新密码。 例如,密文browoanoommnaon可以按以下顺序解密:

1. "browoanoommnaon"
2. "browoannaon"
3. "browoaaon"
4. "browoon"
5. "brown"
When an arbitrary string cryptogram is given as a parameter, 
complete the solution method to return the result of deleting 
consecutive duplicate characters.

Restrictions
A cryptogram is a string that is 1 or more and 1000 or less in length.
The cryptogram consists only of lowercase alphabetic characters.
I/O example
cryptogram result
browoanoommnaon brown
zyelleyz ""
I/O example explanation
I/O example #1
It's like an example of the problem.

I/O example #2
It can be decoded in the following order:

1. "zyelleyz"
2. "zyeeyz"
3. "zyyz"
4. "zz"
5. ""

Tags: oftheintruereturnisexamplecheck
1条回答
网友
1楼 · 发布于 2024-10-01 15:32:01

您可以减少位代码长度

def solution(str1):
    list1 = list(str1)

    while True:
        check = False
        for i in range(len(list1) - 1):
            if list1[i] == list1[i + 1]:
                del list1[i + 1], list1[i]
                check = True
                break
        
        if check:
            continue
        else:
            return ''.join(list1)

print(solution('browoanoommnaon'))

或者你也可以像这样递归地解决它

def solution(str1):
    list1 = list(str1)

    for i in range(len(list1) - 1):
        if list1[i] == list1[i + 1]:
            del list1[i + 1], list1[i]
            return solution(''.join(list1))

    return ''.join(list1)

print(solution('browoanoommnaon'))

不管怎样,你的方法很好

希望我能帮忙

相关问题 更多 >

    热门问题