You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Codewars Last Survivor题目求助:Python代码处理特定输入时出现索引越界错误

Why does my code throw an index out-of-bounds error for the 'zbk' [2,1] test case?

Let's break down exactly what's going wrong here, and fix your code step by step.

First: You're accessing coords[i] when you should just use i directly

Look at your loop logic:

for i in coords:
    new_letters.pop(coords[i])

When your input coords are [2,1], the first iteration sets i = 2. Then you try to get coords[2]—but coords only has 2 elements, so its valid indices are 0 and 1. That's the direct cause of your index out-of-bounds error! You don't need to index into coords here; i already holds the position you want to remove.

Second: You're resetting your working list every time

Your while len(coords) >=1 block reinitializes new_letters = [l for l in letters] on every loop run. That means you never actually build up the state of the string after each removal—you keep starting over from the original string every time, which completely breaks the sequential removal logic you need.

Fixed Code

Here's a corrected version that works for all your test cases:

def last_survivor(letters, coords):
    # Convert the input string to a mutable list once
    current_letters = list(letters)
    # Iterate over each position in the coords array
    for pos in coords:
        # Remove the element at the specified position (adjusted for prior removals)
        current_letters.pop(pos)
    # Return the remaining character as a string
    return ''.join(current_letters)

Let's test this with your problematic case:

For last_survivor('zbk', [2,1]):

  1. Start with ['z','b','k'], pop index 2 → we're left with ['z','b']
  2. Next, pop index 1 → we're left with ['z'], which returns 'z' as expected.

And for last_survivor('kbc', [0,1]):

  1. Start with ['k','b','c'], pop index 0 → ['b','c']
  2. Pop index 1 → ['b'], returns 'b' correctly.

Quick recap of the fixes:

  • Use the loop variable pos directly as the index for pop()—don't try to index into the coords array again.
  • Initialize your mutable list once, not on every loop iteration, so you preserve the state after each removal.
  • The while loop was unnecessary here since we just need to process each coordinate in order exactly once.

内容的提问来源于stack exchange,提问作者Vic2021

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 16:48:11