Which is more pythonic?
Paul Hankin
paul.hankin at gmail.com
Fri Jan 25 04:44:57 EST 2008
benjamin.zimmerman at gmail.com wrote:
> I have a goal function that returns the fitness of a given solution. I
> need to wrap that function with a class or a function to keep track of
> the best solution I encounter. Which of the following would best serve
> my purpose and be the most pythonic?
You could write a function that generates your trial solutions and use
max.
Eg: instead of using your Goal class:
def f(score_function):
goal = Goal(score_function)
while there's more solutions:
... produce trial solution
goal(trial_solution)
return goal.best
Write a solution generator...
def all_solutions():
while there's more solutions:
... produce trial solution
yield trial_solution
...and find the best using
best = max(all_solutions(), key = score_function)
This uses a builtin rather than either of the snippets in the original
post, and it's also a much cleaner approach.
--
Paul Hankin
More information about the Python-list
mailing list