Searching for most pythonic/least stupid way to do something simple

nn pruebauno at latinmail.com
Wed Mar 17 15:29:31 CET 2010



Michael Torrie wrote:
> david jensen wrote:
> > of course, changing nn's to:
> > def getOutcomes(myList=[2,5,8,3,5]):
> >    low_id = int(myList[0]>myList[1])
> >    amountToShare = 2*myList[low_id]
> >    remainder = myList[not low_id]-myList[low_id]
> >    tail=list(myList[2:])
> >    outcomes = [[amountToShare*perc, remainder+amountToShare*(1-perc)]+
> > tail for perc in (1.0, 0.75, 0.5, 0.25, 0.0)] if not low_id else
> > [[remainder+amountToShare*perc, amountToShare*(1-perc)]+ tail for perc
> > in (1.0, 0.75, 0.5, 0.25, 0.0)]
> >    return outcomes
> >
> >
> > works, just hides the ugliness in a more compact form
>
> If Gerard's code works, I would consider it far superior to your code
> here.  Pythonic does not necessarily mean short and ugly, nor does it
> mean that you have to always use list comprehensions.   Having a
> readable algorithm that's easy to follow in the future is a far better
> way than trying to use python's cool features to compact the code to as
> small and unreadable section as possible.
>
> I used to use list comprehension all the time, but I've found that often
> an explicit for loop is a much better solution in terms of
> maintainability.  Especially when you start seeing nested comprehensions
> such as you have here.

To be fair, that list comprehension was unnecessary complicated. The
following version does the same thing and still looks pretty
reasonable IMHO:

def getOutcomes(myList=[2,5,8,3,5]):
   low_id = int(myList[0]>myList[1])
   high_id = not low_id
   smaller = myList[low_id]
   bigger = myList[high_id]
   amountToShare = 2*smaller
   remainder = bigger-smaller
   remain0 = low_id*remainder
   remain1 = high_id*remainder
   tail = list(myList[2:])
   percents = (1.0, 0.75, 0.5, 0.25, 0.0)
   outcomes = [[remain0+amountToShare*perc, remain1+amountToShare*(1-
perc)]
               +tail for perc in percents]
   return outcomes



More information about the Python-list mailing list