PyWart: Language missing maximum constant of numeric types!

Ian Kelly ian.g.kelly at gmail.com
Fri Feb 24 20:26:42 EST 2012


On Fri, Feb 24, 2012 at 10:32 AM, Devin Jeanpierre
<jeanpierreda at gmail.com> wrote:
> On Fri, Feb 24, 2012 at 9:25 AM, Neil Cerutti <neilc at norwich.edu> wrote:
>> The only time I've naively pined for such a thing is when
>> misapplying C idioms for finding a minimum value.
>>
>> Python provides an excellent min implementation to use instead.
>
> min can be a little inconvenient. As soon as anything complicated has
> to be done during the min expression, you need to switch to using
> something else for sanity's sake. In that vein, I do actually
> sometimes use float('inf') (for numbers), or a custom max/min object.
>
> ----
>
> Silly and completely nonserious addendum:
>
> Forgive me, I have spoken in error! min is the one true way, for you
> can still do it with a little wrangling, as follows:
>
>    @operator.itemgetter(1)
>    @min
>    @apply
>    def closest_object():
>        for x in xrange(board_width)
>            for y in xrange(board_height):
>                try:
>                    entity = board.get_entity(x, y)
>                except EntityNotFound:
>                    pass
>                else:
>                    yield distance(player.pos, entity.pos), entity

Cute, but what's so terrible about:

    def all_entities():
        for x in xrange(board_width):
            for y in xrange(board_height):
                try:
                    yield board.get_entity(x, y)
                except EntityNotFound:
                    pass

    closest_object = min(all_entities,
        key=lambda e: distance(player.pos, e.pos))

Especially given that all_entities should be reusable in other contexts.

Cheers,
Ian



More information about the Python-list mailing list