1

I am having trouble with the code below:

def myprogram(x):
    if x == []:
        return x
    else:
        return myprogram(x[1:]) + [ x[0] ]

What is the parameter type (x)? What does this function do?

I'm supposed to write code that calls this function with a parameter and find the return value, but i can't do that without understanding what is going on here. any help/feedback would be appreciated.

4

2 回答 2

7

Since this is clearly homework, I'll limit my answer to a hint.

I'm supposed to write code that calls this function

It is clear that the function is expecting a list. I leave it to you to figure out the rest.

If you are unsure how to proceed, you could try to call it with various lists to see what it returns. However, ultimately you will have to read and understand the source code to be certain about what the function does.

于 2012-12-14T18:31:41.310 回答
0

那是一个递归函数,它继续调用自己,直到终止条件停止它

例如,如果您运行以下代码:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n -1)

如果您调用 with ,您期望返回factorial(5)什么?

关于如何在此处制作它们的另一篇文章:如何在 python 中构建递归函数?

于 2012-12-14T19:27:46.643 回答