【发布时间】:2019-11-04 11:59:52
【问题描述】:
我有一个输入文件如下
3
01
0010100
11011
输出应该是这样的
LIVES
DIES
LIVES
但是我的代码返回,
DIES
[1, 0]
DIES
[0, 1, 0, 0, 0, 1, 0]
DIES
[1, 1, 0, 1, 1]
我正在解决这个问题 (https://open.kattis.com/problems/whowantstoliveforever)。基本上,我正在查看位置 i-1 和 i+1 的位的当前值(如果它们存在;否则假设它们为 0)。如果我的程序恰好看到一个 1,那么第 i 位的下一个值为 1,否则为 0。所有位同时更改,因此下一个状态的新值仅取决于前一个状态的值.如果宇宙只包含零,它就是死的。
我想说如果程序捕获到无限循环,这可能意味着宇宙将继续存在,0 和 1 会不断重复。如果len(set(x)) 为 1,那么我将返回 False。
import sys
def get_bit(bits, i):
if 0 <= i < len(bits):
return int(bits[i])
else:
return 0
def print_result(boolean):
print("LIVES" if boolean else "DIES")
def recursion(in_list, output_list):
try:
for index in range(len(in_list)):
if (get_bit(in_list, index-1) == 0 and get_bit(in_list, index+1) == 0) or (get_bit(in_list, index-1) == 1 and get_bit(in_list, index+1) == 1):
output_list.append(0)
elif(get_bit(in_list, index-1) == 0 and get_bit(in_list, index+1) == 1) or (get_bit(in_list, index-1) == 1 and get_bit(in_list, index+1) == 0):
output_list.append(1)
if len(set(output_list)) == 1:
return False
else:
in_list = output_list
output_list = []
recursion(in_list, output_list)
except RuntimeError:
return True
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)
output_list = []
print_result(recursion(_list, output_list))
print(output_list)
如果不是except RuntimeError 不起作用,有什么办法可以解决这个问题?
【问题讨论】:
-
请在问题本身中解释您的问题。
-
@Blorgbeard 谢谢,更新了。
-
好的,尝试根据递归限制错误来检测是错误的方法。您需要跟踪以前的状态并检测何时进入您已经看到的状态。如果发生这种情况,您就知道存在循环或稳定(非死)状态。
-
而且不要递归,重构回迭代。
-
@Blorgbeard 当我尝试迭代时,我认为很难确切知道何时停止。
标签: python python-3.x python-2.7 error-handling runtime-error