# Mystery computation in Python (square root)
# Takes input n and computes output named result

import simplegui

# global state

result = 1
iteration = 0
max_iterations = 10

# helper functions

def init(start):
    """Initializes n."""
    global n
    n = start
    print "Input is", n
    
def get_next(current):
    """???  Part of mystery computation."""
    return 0.5 * (current + n / current)

# timer callback

def update():
    """???  Part of mystery computation."""
    global iteration, result
    iteration += 1
    # Stop iterating after max_iterations
    if iteration >= max_iterations:
        timer.stop()
        print "Output is", result
    else:
        result = get_next(result)

# register event handlers

timer = simplegui.create_timer(1, update)

# start program
init(13)
timer.start()



# consider the sequence of numbers generated by repeatedly following the rule:
# divide by two if the number is even or
# multiply by 3 and add 1 if the number is odd.
# 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1

import simplegui

result = 0

def init(start):
    global result
    result = start
    print "Input is", result

def get_next(current):
    if current % 2 == 0:
        return current / 2
    else:
        return (current * 3) + 1
        
def update():
    global result
    if result == 1:
        timer.stop()
    else:
        result = get_next(result)
        print result

timer = simplegui.create_timer(1, update)

init(217)

timer.start()


