Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Babbage's Difference Engine in Python
def diff(seq):
""" [1,4,9] => [3,5] """
return map(lambda x,y: x-y, seq[1:], seq[:-1])
def triangle(seq):
""" [1,4,9] => [[1,4,9],[3,5],[2]] """
diffs=[seq]
for i in range(1, len(seq)):
diffs.append(diff(diffs[i-1]))
return diffs
def reductions(seq):
""" [1,4,9] => [1,5,14] """
l = [seq[0]]
for i in range(1, len(seq)):
l.append(seq[i]+l[i-1])
return l
def infer(pattern, n):
""" infer([1,4,9], 10) => [1,4,9,16,25 ... 100] """
gen_seq = [seq[-1] for seq in triangle(pattern)]
gen_seq.reverse()
elements = pattern[:-1]
for count in range(len(pattern)-1, n):
elements.append(gen_seq[-1])
gen_seq = reductions(gen_seq)
return elements
Owner

divs1210 commented Oct 14, 2014

This is a Python port of some Clojure code that I wrote about some time back in a blog post .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment