【问题标题】:List index out of range when solving a Kattis Problem解决 Kattis 问题时列出超出范围的索引
【发布时间】:2019-06-20 15:16:51
【问题描述】:

我正在解决这个问题 (https://open.kattis.com/problems/whowantstoliveforever)。由于_list[index-1] == "0"_list[index+1] == "0",我的列表索引超出了范围,而且它显然不存在。我想知道是否有更好的方法来解决这个问题。

下面是我的代码。

import sys


def liveForever(input_list):
    if len(set(input_list)) < 1:
        return True
    else:
        return False
    return False


def print_result(boolean):
    print("LIVE" if boolean else "DIES")


num_cases = int(sys.stdin.readline().strip())
for i in range(num_cases):
    _list = []
    case = sys.stdin.readline().strip()
    for char in case:
        _list.append(char)
    for index in range(len(_list)):
        if (_list[index-1] == "0" and _list[index+1] == "0") or (_list[index-1] == "1" and _list[index+1] == "1"):
            _list[index] == "0"
        elif(_list[index-1] == "0" and _list[index+1] == "1") or (_list[index-1] == "1" and _list[index+1] == "0"):
            _list[index] == "1"
        print(_list)
    print_result(liveForever(_list))

这里基本上我的输出需要是基于列表的 LIVES 或 DIES。

【问题讨论】:

  • 在循环的最后一次迭代中访问_list[index+1] 会发生什么?
  • 你有没有尝试输入for index in range(len(_list)-1):,我想它可能会成功
  • @DeepSpace 它应该假设空的超出范围的列表元素为 0,它与 _list[index(0) - 1] 相同
  • 问题出在+1。索引-1 在 Python 中有效。它获取列表的最后一个元素,这不是您想要的。

标签: python python-3.x python-2.7 list


【解决方案1】:

套用一句老医生的笑话,如果有什么东西让你的程序崩溃,then don't do that.

The assignment 明确指定任何超出有效范围的位的值都假定为零。因此,在访问列表之前,只需检查索引是否超出范围,如果超出则返回零。一种方法是使用包装函数,例如:

def get_bit(bits, i):
    if 0 <= i < len(bits):
        return bits[i]
    else:
        return 0

还有其他可能更有效的方法来实现相同的结果,但我将优化代码作为它应该做的练习。

附言。请注意,您的代码还具有(至少)另一个错误:您正在修改位列表,因为您正在迭代它。由于下一个时间步的位状态应该取决于上一步中这些位及其邻居的状态,它们被更新之前,这将给出不正确的结果。要使其工作,您需要有两个列表,以便您可以将更新的值存储在一个中,同时从另一个中读取旧值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-20
    • 2020-04-23
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    相关资源
    最近更新 更多