Skip to content

Instantly share code, notes, and snippets.

@elucid
Created July 21, 2010 03:56
Show Gist options
  • Save elucid/484033 to your computer and use it in GitHub Desktop.
Save elucid/484033 to your computer and use it in GitHub Desktop.
# original implementation by jcl; see http://pastie.org/777044
import time
start_time = time.time()
_eq_map_cache = {}
#
def get_eq_map(vals):
# Given a list of floating point values, returns a map from result values
# to an equation string returning that result.
global _eq_map_cache
if tuple(vals) not in _eq_map_cache:
eq_map = {}
if len(vals) == 1:
eq_map[vals[0]] = str(vals[0])
else:
for i in range(1, len(vals)):
head_eq_map = get_eq_map(vals[:i])
tail_eq_map = get_eq_map(vals[i:])
for h,heq in head_eq_map.iteritems():
heq2 = "(" + heq
for t,teq in tail_eq_map.iteritems():
teq2 = teq + ")"
eq_map[h + t] = heq2 + "+" + teq2
eq_map[h - t] = heq2 + "-" + teq2
eq_map[h * t] = heq2 + "*" + teq2
if t != 0:
eq_map[h / t] = heq2 + "/" + teq2
_eq_map_cache[tuple(vals)] = eq_map
return _eq_map_cache[tuple(vals)]
#
all_vals = get_eq_map([float(x) for x in range(1, 10)])
print 'Time:', time.time() - start_time
print 'Total number of values', len(all_vals)
for i in (float(x) for x in range(1900, 2101)):
if i in all_vals:
print i, all_vals[i]
else:
print i, 'None'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment