gpt4 book ai didi

python - 在递归中仅应用一次条件

转载 作者:行者123 更新时间:2023-12-02 18:13:02 25 4
gpt4 key购买 nike

我只想在递归中应用一次条件。我的数据结构如下所示

stages = {"stage_1": False, "stage_2":False, "stage_3":False,"state_4": False}

我想从中随机选择任何阶段并将状态更改为 True。但是当 true 阶段总数为 3 时,我想随机将 True 阶段更改为 False。但只有一次。然后它应该继续将阶段变为 True。当所有 4 个阶段都为真时。递归过程停止。我怎样才能做到这一点 ?我已经尝试过以下代码。但它并不完整。

def process(stages):
all_stages = [stage for stage, status in stages.items() if status == False]
if len(all_stages) !=0:
print(all_stages)
select_ = random.choice(all_stages)
print("\tselected stage: ",select_)

stages[select_] = True
process(stages)
else:
print("Done")
print(stages)

process(stages)

无需添加额外条件即可工作。我已经尝试过以下一种。但这不起作用

def process(stages):
all_stages = [stage for stage, status in stages.items() if status == False]
if len(all_stages) !=0:
print(all_stages)
select_ = random.choice(all_stages)
print("\tselected stage: ",select_)

stages[select_] = True

if len(all_stages) == 1:
select_ = random.choice([stage for stage, status in stages.items() if status == True])
stages[select_] = False
process(stages)
else:
print("Done")
print(stages)

process(stages)

最佳答案

代码是@NoBlockhit的建议

stages = {"stage_1": False, "stage_2":False, "stage_3":False,"state_4": False}

status = True
def process(stages):
global status
print(status)
all_stages = [stage for stage, status in stages.items() if status == False]
if len(all_stages) !=0:
print(all_stages)
select_ = random.choice(all_stages)
print("\tselected stage: ",select_)

stages[select_] = True

if status:
if len(all_stages) == 1:
select_ = random.choice([stage for stage, status in stages.items() if status == True])
stages[select_] = False
status = False
process(stages)
else:
print("Done")
print(stages)

process(stages)

关于python - 在递归中仅应用一次条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72014676/

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