Recursion

Christophe Delord christophe.delord at free.fr
Fri Jul 19 02:31:05 EDT 2002


Try this:

def bits(x):
	return (x!=1 and bits(x>>1) or "") + "01"[x&1]

The idea is to return the string instead of printing it.

or this if you prefer:

def bits(x):
	if x != 1:
		s = bits(x>>1)
	if x & 1:
		s = s+"1"
	else
		s = s+"0"
	return s

On Fri, 19 Jul 2002 05:55:53 +0000 (UTC)
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,
> 


-- 

(o_   Christophe Delord                   _o)
//\   http://christophe.delord.free.fr/   /\\
V_/_  mailto:christophe.delord at free.fr   _\_V



More information about the Python-list mailing list