vendredi 8 mai 2015

Using while or if as a condition for recursion leads to different results

This is a simple recursive function that should run 10 times, the condition is if.

count = 0  
def recurse(count):
    *if* count < 10:
        print count
        count += 1
        recurse(count)

recurse(count)

Output

0 1 2 3 4 5 6 7 8 9 OK

When I use a while loop, the results are wildly different and I don't understand why it does not output 0 to 9.

Code

count = 0
def recurse(count):
    *while* count < 10:
        print count
        count += 1
        recurse(count)

recurse(count)

Output

0 1 2 3 4 5 6 7 8 9 9 8 9 9 7 8 9 9 8 9 9 6 7 8 9 9 8 9 9 7..... 8 9 9

You can try it here http://ift.tt/XiergB, I don't know how to create a link with the code though.

anyone see what I am doing wrong.

Edit.

Output of code 2 is finite.

Example using 3 as a limit.

  • using if 0 1 2
  • using while 0 1 2 2 1 2 2

Aucun commentaire:

Enregistrer un commentaire