Thread: Mystery Code

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

    Join Date
    Dec 2012
    Rep Power

    Mystery 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 God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Rep Power
    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