Recursion

Paul Rubin phr-n2002b at NOSPAMnightsong.com
Fri Jul 19 03:27:33 EDT 2002


Abhijit Soman <abhijit_som at yahoo.co.in> writes:
> 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,

I think the most direct translation is:

def showbits(x):
  r = ''
  if x != 1:
    r = showbits(x >> 1)
  if x & 01:
    r = r + '1 '
  else:
    r = r + '0 '
  return r



More information about the Python-list mailing list