Recursion
William Park
opengeometry at NOSPAM.yahoo.ca
Fri Jul 19 04:02:37 EDT 2002
Abhijit Soman <abhijit_som at yahoo.co.in> wrote:
> In the recursive function below i want to add the individual bits to a
> string and return that string to the caller
> Can anyone tell me how to do that
>
>
> def showbits(x):
> if x != 1:
> showbits(x >> 1)
> if x & 01:
> print 1,
> else:
> print 0,
You forgot to return string '1' or '0', and then append to output. Try
def showbits(x):
if x == 0: return ''
if x & 1:
return showbits(x>>1) + '1'
else:
return showbits(x>>1) + '0'
--
William Park, Open Geometry Consulting, <opengeometry at yahoo.ca>
8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin
More information about the Python-list
mailing list