+ return self.string
+
+ def get_favored_results(self, error=5):
+ """Calculate the set of most-favored results. A higher error
+ will cause this method to be more reticent about adding new
+ items."""
+ results = self.result_urls.values_list('pk', 'url',)
+
+ result_dict = {}
+ for pk, url in results:
+ result_dict[pk] = {'url': url, 'value': 0}
+
+ clicks = Click.objects.filter(result__pk__in=result_dict.keys()).values_list('result__pk', 'datetime')
+
+ now = datetime.datetime.now()
+
+ def datetime_value(dt):
+ days = (now - dt).days
+ if days < 0:
+ raise ValueError("Click dates must be in the past.")
+ if days == 0:
+ value = 1.0
+ else:
+ value = 1.0/days**2
+ return value
+
+ for pk, dt in clicks:
+ value = datetime_value(dt)
+ result_dict[pk]['value'] += value
+
+ #TODO: is there a reasonable minimum value for consideration?
+ subsets = {}
+ for d in result_dict.values():
+ subsets.setdefault(d['value'], []).append(d)
+
+ # Now calculate the result set.
+ results = []
+
+ def cost(value):
+ return error*sum([(value - item['value'])**2 for item in results])
+
+ for value, subset in sorted(subsets.items(), cmp=lambda x,y: cmp(y[0], x[0])):
+ if value > cost(value):
+ results += subset
+ else:
+ break
+ return results