-1
def mystery(l):
    if l == []:
        return(l)
    else:
        return(mystery(l[1:])+l[:1])
mystery([22,14,19,65,82,55])

#output: [55, 82, 65, 19, 14, 22]

Please explain how this code is working. I am not able to understand the recursion part here.

Amit Amola
  • 2,301
  • 2
  • 22
  • 37
  • 3
    You should either run the code through a [debugger](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) or throw in some `print` statements and watch what it is doing step-by-step. – 0x5453 Dec 15 '20 at 18:20
  • 1
    Please share what you _do_ understand about the code – tehhowch Dec 15 '20 at 18:21
  • Have you tried following the code on [PythonTutor](http://pythontutor.com/visualize.html#mode=edit)? – Mr. T Dec 15 '20 at 18:45

3 Answers3

2

It's done by list slicing. By returning

mystery(I[1:]) + I[:1]

you just keep going recursive and adding the first element from the list leftover.

for example:

mystery([1,2,3]) -> return mystery([2,3]) + [1] -> return mystery([3]) + [2] + [1]

and so on

Karol Adamiak
  • 141
  • 1
  • 9
2

The recursive part is the following line:

return (mystery(l[1:]) + l[:1])

Observe that l[:1] (i.e., l[0:1]) is the list consisting of the first element of l and l[1:] (i.e., l[1:len(l)]) is the list consisting of the remaining part of l. The + concatenates lists. Thus,

mystery([1,2,3,4]) = mystery([2,3,4]) + [1]
                   = mystery([3,4]) + [2] + [1]
                   = mystery([4]) + [3] + [2] + [1]
                   = mystery([]) + [4] + [3] + [2] + [1]
                   = [] + [4] + [3] + [2] + [1]
                   = [4,3,2,1]

Therefore, mystery(l) is the reverse of l. That is,

mystery(l) = l[::-1]
evenodd
  • 317
  • 1
  • 8
1

Let's follow an example, each line is equivalent to the one after it:

mystery([22,14,19,65,82,55])
mystery([22,14,19,65,82,55][1:]) + [22,14,19,65,82,55][:1]
mystery([14,19,65,82,55]) + [22]
mystery([14,19,65,82,55][1:]) + [14,19,65,82,55][:1] + [22]
mystery([19,65,82,55]) + [14] + [22]
...
mystery([19,65]) + [82] + [55] + [14] + [22]
mystery([19,65][1:]) + [19, 65][:1] + [82] + [55] + [14] + [22]
mystery([65]) + [19] + [82] + [55] + [14] + [22]
mystery([65][1:]) + [65][:1] + [19] + [82] + [55] + [14] + [22]
mystery([]) + [65] + [19] + [82] + [55] + [14] + [22]
[] + [65] + [19] + [82] + [55] + [14] + [22]
[65, 19, 82, 55, 14, 22]

If you don't understand what [:1] [1:] means please read this SO question.

Roy Cohen
  • 1,540
  • 1
  • 5
  • 22