Interesting math problem

Terry Reedy tjreedy at udel.edu
Tue Mar 18 22:28:10 EDT 2008


"Jeff Schwab" <jeff at schwabcenter.com> wrote in message 
news:C6SdnWmXtYoncELanZ2dnUVZ_ubinZ2d at comcast.com...
| Marc Christiansen wrote:
| > This was my first thought, too. But tailcall optimisation wouldn't help
| > here. `make_slope` is not tail recursive, the `+` (aka list.extend) 
gets
| > executed after the recursion.
|
|
| def make_slope(distance, parts, L=()):
|     if parts == 0:
|         return L
|
|     q, r = divmod(distance, parts)
|
|     if r and parts % r:
|         q += 1
|
|     return make_slope(distance - q, parts - 1, (q,) + L)

So mechanically rewrite (not tested) as

def make_slope(distance, parts, L=()):
    if parts < 0: raise ValueError('do you want me to return?') #added
    while parts:
        q,r = divmod(distance, parts)
        if r and parts % r: q += 1
        distance, parts, L = distance-q, parts-1, (q,) + L
    return L

tjr






More information about the Python-list mailing list