【问题标题】:Pop from empty list error ONLY on lists with even number of elements [duplicate]仅在具有偶数个元素的列表上从空列表错误弹出[重复]
【发布时间】:2016-09-13 19:29:25
【问题描述】:

所以这只是我在 codewars.com 上做的一个有趣的练习。关键是通过获取最后一个字符并将其添加到字符串中,获取第一个字符并将其添加到另一个字符串,直到您有 1 (对于具有奇数个字母的字符串)或剩下 0(对于偶数个字母的字符串)字符。如果您有兴趣,这里是challenge 的链接。

def pop_shift(test):
    firstSol = []
    secondSol = []
    testList = list(test)
    while len(testList) != 1:
        firstSol.append(testList.pop())
        secondSol.append(testList.pop(0))
    return [''.join(firstSol), ''.join(secondSol), ''.join(testList)]

如果字符串有奇数个字符,我的代码会给我正确的结果:

['erehtse', 'example', 't']

但是偶数个字符我得到这个错误:

Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    pop_shift("egrets")
  File "<pyshell#35>", line 6, in pop_shift
    firstSol.append(testList.pop())
IndexError: pop from empty list

我查看了一堆涉及 pop() 方法的问题,但没有一个听起来与此非常相似。我还用各种字符串对此进行了测试,并查看了 pop 方法的文档。一定有什么我错过了。任何指针表示赞赏。这也是我的第一个问题,如果您还有什么想看的,请告诉我。

【问题讨论】:

  • 这将是学习使用调试器的好机会。

标签: python list


【解决方案1】:

您需要:while len(testList) &gt; 1,而不是 while len(testList) != 1,因为 len(testList) 将在“偶数”字符串上从 2 跳转到 0

def pop_shift(test):
    firstSol = []
    secondSol = []
    testList = list(test)
    while len(testList) > 1:
        firstSol.append(testList.pop())
        secondSol.append(testList.pop(0))

    return [''.join(firstSol), ''.join(secondSol), ''.join(testList)]

然后:

print(pop_shift("Monkeys"))
> ['sye', 'Mon', 'k']

print(pop_shift("Monkey"))
> ['yek', 'Mon', '']

【讨论】:

  • @erenk 不客气!单个角色如何改变行为...
【解决方案2】:

您的循环正在检查列表的长度是否不是 1;对于偶数长度的列表,因为您总是一次弹出 2 个项目,所以它永远不会看到长度为 1。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 2022-01-06
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多