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.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Jack
  • 17
  • 2
  • http://docs.python.org/2/tutorial/introduction.html About half way down that page will help you figure out some of the syntax as well. – sean Dec 14 '12 at 18:34
  • 5
    One good way to figure it out is to run this and try calling the function with different values of `x` – Stuart Dec 14 '12 at 18:37

2 Answers2

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

That is a recursive function, it continues calling itself until the termination condition stops it

For example, if you run this code:

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

what would you expect would return if you invoke with factorial(5)?

Another post on how to make them here: How can I build a recursive function in python?

Community
  • 1
  • 1
jackcogdill
  • 4,900
  • 3
  • 30
  • 48