Interesting math problem
Jeff Schwab
jeff at schwabcenter.com
Tue Mar 18 12:29:00 EDT 2008
Marc Christiansen wrote:
> sturlamolden <sturlamolden at yahoo.no> wrote:
>> On 18 Mar, 00:58, Jeff Schwab <j... at schwabcenter.com> wrote:
>>
>>> def make_slope(distance, parts):
>>> if parts == 0:
>>> return []
>>>
>>> q, r = divmod(distance, parts)
>>>
>>> if r and parts % r:
>>> q += 1
>>>
>>> return [q] + make_slope(distance - q, parts - 1)
>> Beautiful. If Python could optimize tail recursion, it would even run
>> fast.
>
> 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)
More information about the Python-list
mailing list