我对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
下面是要修改的代码(不允许循环for
和while
)
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
类型,这对我来说是全新的。在此示例中,我想知道如何在没有for
或while
循环的情况下实现递归。
答案 0 :(得分:1)
代替
for i in range(0, depth):
sys.stdout.write(' ')
要打印的空格数是depth
的两倍,您可以这样做
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)
递归函数必须具有退出条件,以防止它成为无限递归。
这里,仅在字典中有有效键且值不是空字符串的情况下,才进行递归。
who in StorySequence
用于检查字典who
中是否存在具有StorySequence
内容的键。