0
a=[1,2,3,4,5]
b=[1,2,3,4,5,5,5,5,5,55,5,5,5,5,5,5,5,5,5,5,5,5,5,5]
def func(a,b):
    for i in range(5):
        
        if a[i]>3:
            print(len(b))
            b.pop()
            if not b:
                print("cc")
                return "tt"
            func(a,b)
    if len(b)==2:
        return "l"
    return "t"

print(func(a,b))

The output I got for len(b) is like this. Why the tt is not output and generate an error for empty list? 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 cc 0

def hanoi(n,x,y,z):
    if n == 1:
        z.append(x.pop())
        return
    else:
        hanoi(n-1,x,z,y)
        hanoi(1,x,y,z)
        hanoi(n-1,y,x,z)
        
hanoi(len(A),A,B,C)

I saw hanoi tower code to modify mine. I'm wondering where is the differences without return? Why my code cannot stop but hanoi problem code can stop as soon as reaching the end?

4
  • 2
    You need to return your recursion. return func(a, b). Commented Aug 6, 2020 at 18:53
  • In any case, it is not usually a good idea for functions to both modify their (mutable) arguments and also return a value, because this can lead to confusion about what they are supposed to do. One or the other. Commented Aug 6, 2020 at 18:58
  • so if not add return. The function will run only but not return a value? But why it is not stopped? I saw from hanoi tower problem. 1 def hanoi(n,x,y,z): 2 if n == 1: 3 z.append(x.pop()) 4 return 5 else: 6 hanoi(n-1,x,z,y) 7 hanoi(1,x,y,z) 8 hanoi(n-1,y,x,z) 9 10 hanoi(len(A),A,B,C) They didn't return it why it can stop? Commented Aug 6, 2020 at 19:05
  • Please don't post images of code, data, or Tracebacks. Copy and paste it as text then format it as code (select it and type ctrl-k) ... Discourage screenshots of code and/or errors Commented Aug 6, 2020 at 19:12

2 Answers 2

1

The result of func(a,b) as used recursively is never returned. Change the line func(a,b) to return func(a,b). Then you'll get your tt's.

Sign up to request clarification or add additional context in comments.

1 Comment

so if not add return. The function will run but not return a value?
1

You should return line 12. func(a,b) to return func(a,b).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.