Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

While loop doesn't honor the constraint

The below line of code runs however the while loop doesn't stop when len(fib_list) reaches < 20. It continues instead to add on to the list albeit backwards. Any ideas?

fib_list = [0,1]


def fib(n, sum):
    while len(fib_list) < 20:
        for i in range(n, len(fib_list)):
            sum += fib_list[i]
            n += 1
            print(n, sum, len(fib_list))
            fib_list.append(sum)
            fib(n, sum)
        else:
            break
        
fib(0, 0)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have a for loop in the while loop and a recursive call in the for loop. This is very bad practice in general and will cause you many headaches. It doesn't stop when len(fib_list) reaches 20 because as long as the while loop execute once, your for loop and the recursive calls will execute. In your recursive call, len(fib_list) could be < 20 and it will go into the while loop, starting the for loop once again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...