gpt4 book ai didi

Python 使用列表时输入错误

转载 作者:太空宇宙 更新时间:2023-11-03 20:43:24 24 4
gpt4 key购买 nike

我正在解决这个问题( https://open.kattis.com/problems/whowantstoliveforever )。正如问题所述,我的程序必须根据输入的 0 和 1 来确定宇宙是存在还是死亡。

to determine the next value of the i-th bit, look at the current value of the bits at positions i−1 and i+1 (if they exist; otherwise assume them to be 0). If you see exactly one 1, then the next value of the i-th bit is 1, otherwise it is 0. All the bits change at once, so the new values in the next state depend only on the values in the previous state. We consider the universe dead if it contains only zeros.

我当前的解决方案适用于示例输入文件,但是将其提交给 Kattis 时失败。 (错误答案)

下面是我的代码。

import sys


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


def get_new_state(old_state):
new_state = []
for index in range(len(old_state)):
if (get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 0) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 1):
new_state.append(0)
elif(get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 1) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 0):
new_state.append(1)
return new_state


def is_dead(state):
if len(set(state)) == 1:
return True
else:
return False


def foresee_fate(state):
seen = []
while True:
if is_dead(state):
return False
if state in seen:
return True
seen.append(state)
state = get_new_state(state)


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


num_cases = int(sys.stdin.readline().strip())
for i in range(num_cases):
cur_state = []
case = sys.stdin.readline().strip()
for char in case:
cur_state.append(char)
print_result(foresee_fate(cur_state))

请让我知道我可以做些什么来改进这个程序。

最佳答案

按照建议,我已将以下内容添加到我的代码中,现在它可以工作了。然而,我遇到了一个新问题。现在我收到“超出时间限制”> 3.00 秒

def is_dead(state):
if set(state).pop() == 1:
return False
elif len(set(state)) == 1:
return True
else:
return False

如果有任何解决此问题的建议,请告诉我

关于Python 使用列表时输入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56741457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com