【发布时间】: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