''' Code that uses an autoregressive model to predict
     the next integer in the sequence. Who knew something from
     time-series analysis would be useful here? I wouldn't.
'''

from scipy import array, ceil, floor, randn, array
from statsmodels.tsa import ar_model

def pred(seq):
    model_to_fit = ar_model.AR(seq)
    fitted= model_to_fit.fit()
    kar = model_to_fit.k_ar # order of the model
    return floor(fitted.predict(len(seq),len(seq)))

# sequence that is not generated by
# a recurrence relation
seq = [1,2,3,6,11,23,47,106]
nval= 235

# this fails, but not by a lot
print pred(seq), nval

# something more difficult, fails
seq = [1, 1, 2, 3, 4, 10, 8, 23, 27, 70]
nval = 56
print pred(seq), nval

# gets that right! 
seq = [1, 2, 3, 4, 10, 11, 12, 13, 14, 15]
nval = 16
print pred(seq), nval

# constant sequence
try :
    # this fails cause there is not enough
    # variability in the data :( 
    seq = [0,0,0,0,0,0,0]
    nval = 0
    print pred(seq)
    print nval
except ValueError:
    print "There was a ValueError above. :-("
    print "It's easy to catch though."
