Top level of a recursive function

Michael F. Stemper michael.stemper at gmail.com
Tue Dec 13 15:28:26 EST 2022


On 13/12/2022 09.03, Stefan Ram wrote:
> "Michael F. Stemper" <michael.stemper at gmail.com> writes:
>> def fred(cf,toplevel=True):
>>    x = cf[0]
>>    if len(cf)>1:
>>      if toplevel:
>>        return x + fred(cf[1:],False)
>>      else:
>>        return "(" + x + fred(cf[1:],False) + ")"
>>    else:
>>      if toplevel:
>>        return x
>>      else:
>>        return "(" + x + ")"
> 
> def rest( s ):
>      return "(" + s[ 0 ] +( rest( s[1:] ) if len( s )> 1 else '' )+ ')'
> 
> def nest( s ):
>      return( s[ 0 ] if s else '' )+( rest( s[1:] )if len( s )> 1 else '' )

Hey, that's slick! And if I define rest within nest, it's not going
to be externally accessible.

Thanks

-- 
Michael F. Stemper
No animals were harmed in the composition of this message.


More information about the Python-list mailing list