gpt4 book ai didi

python - 没有 for 或 while 循环的字典递归

转载 作者:行者123 更新时间:2023-12-01 08:30:22 25 4
gpt4 key购买 nike

我对 Python 还很陌生,而且我已经对你们中的许多人可能觉得小菜一碟的东西提出了挑战。输出必须是:

The Monkey-child could not fall asleep, so the mother told him a story, he was once a Tiger-child
The Tiger-child could not fall asleep, so the mother told him a story, he was once a Human-child
The Human-child could not fall asleep, so the mother told him a story, he was once a Panther-child
The Panther-child could not fall asleep, so the mother told him a story, he was once a Snake-child
The Snake-child has tired and fell asleep
The Panther-child has tired and fell asleep
The Human-child has tired and fell asleep
The Tiger-child has tired and fell asleep
The Monkey-child has tired and fell asleep

要修改的代码如下(不允许使用forwhile循环):

 import sys

StorySequence = {
"Monkey": "Tiger",
"Tiger": "Human",
"Panther": "Snake",
"Snake": "",
"Human": "Panther"
}

def writePaddingForDepth(depth):
for i in range(0, depth):
sys.stdout.write(' ')
sys.stdout.flush()

def endStory(thread, depth):
writePaddingForDepth(depth)
print ("The " + thread + "-child has tired and fell asleep.")
return True

def startStory(thread, depth):
if (len(StorySequence[thread]) == 0):
return endStory(thread, depth)

writePaddingForDepth(depth)

print ("The " + thread + "-child could not fall asleep, "
"so the mother told him a story, he was once "
+ StorySequence[thread] + "-child")

## Code here

startStory("Monkey", 0)

我试图像处理 C 中的数组一样处理它,但显然不是,据我所知,它是一个 dict 类型,这对我来说是全新的。我想知道如何在此示例中实现没有 forwhile 循环的递归。

最佳答案

而不是做

for i in range(0, depth):
sys.stdout.write(' ')

要打印两倍于深度的空格数,您可以这样做

sys.stdout.write('  ' * depth)
<小时/>

你可以做类似的事情

def fn(who, depth):
if(who in StorySequence):
if(StorySequence[who]!=''):
print ("\t" * depth + "The " + who + "-child could not fall asleep, "
"so the mother told him a story, he was once "
+ StorySequence[who] + "-child")
fn(StorySequence[who], depth+1)
print ("\t" * depth + "The " + who + "-child has tired and fell asleep.")

fn("Monkey", 0)

递归函数必须有退出条件,以防止其成为无限递归。

这里,只有当字典中有有效的键并且值不是空字符串时才会进行递归。

StorySequence中的

who用于检查字典StorySequence中是否存在具有who内容的键。

关于python - 没有 for 或 while 循环的字典递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53930981/

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