[Tutor] Bit Strings [a recursive approach]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Oct 23 16:49:51 EDT 2003



On Thu, 23 Oct 2003, Blake Winton wrote:

> > def bitstrings(n):
> >     if n == 0: return []
> >     if n == 1: return ["0","1"]
> >     return [ digit+bitstring for digit in bitstrings(1)
> >                              for bitstring in bitstrings(n-1) ]
>
> Along those lines, I've always thought that n=0 should
> really return [""].


> def bitstrings(n):
>     if n == 0: return [""]
>     return [ digit+bitstring for digit in ["0","1"]
>                              for bitstring in bitstrings(n-1) ]


Hi Blake,

You're absolutely right!  I didn't think about the empty case clearly
enough.  There is only one bit-string of length 0, and your fix accounts
for this.  Now the bitstrings() function is very beautiful.  *grin*


Thanks again for the correction!




More information about the Tutor mailing list