Thread: Mystery Code

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    8
    Rep Power
    0

    Mystery Code


    Code:
    def mystery(x): 
    
    a = [0, 4, 0, 3, 2]
    while x > 0:
    x = a[x]
    return "Done"

    What is the value which cause the program to run forever?
    I do not know the answer please help me. An explanation is GREATLY appreciated. I need a explanation for this.
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,894
    Rep Power
    481
    Let's see here.

    x is a function argument.

    We could try calling the function with one parameter.
    >>> mystery('hello world')

    Ooh! Failure.


    Let's look at the function guts.
    It compares x with 0. Maybe x should be a number.
    And we see that if x has to be positive or the program will quit. Now we can try


    >>> mystery(2.718)

    Oooph. Failure!



    OH! x needs to be a positive integer.
    Greater than 0 but less than the length of the short list.

    Now we can trace the program execution for values in range(1,len(a))
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo