-6

I don't understand how do I assign this function to an identifier? Should I make it a list or something? I need to print the return values but I am unable to do so. Please help me out.

def mystery(l):
    if len(l)<2:
        return (1)
    else:
        return (mystery(l[1:])+[l[0]])

ll= [17,12,41,28,25]
new[:]=mystery(ll)
print(ll)

The error:

Traceback (most recent call last):   
File "Test2.py", line 8, in <module>
  new[:]=mystery(ll)   
  File "Test2.py", line 5, in mystery
    return (mystery(l[1:])+[l[0]])   
    File "Test2.py", line 5, in mystery
      return (mystery(l[1:])+[l[0]])   
      File "Test2.py", line 5, in mystery
        return (mystery(l[1:])+[l[0]]) 
TypeError: unsupported operand type(s) for +: 'int' and 'list'

1 Answers1

1

Try this,

def mystery(l):
    if len(l)<2:
        return [1] # change here
    else:
        return (mystery(l[1:])+[l[0]])

print(mystery(ll))
# output: [1, 28, 41, 12, 17]
Taku
  • 31,927
  • 11
  • 74
  • 85
Rahul K P
  • 15,740
  • 4
  • 35
  • 52