[Tutor] Bit Strings [a recursive approach]

Alan Gauld alan.gauld at blueyonder.co.uk
Wed Oct 22 04:36:44 EDT 2003


> Here's the punchline: things will work if we take a leap of faith,
and
> just write:
>
> ###
> def bitstrings(n):
>     if n == 0: return []
>     if n == 1: return ["0", "1"]
>     if n == 2: return ["00", "01", "10", "11"]
>     else:
>         return (appendInFront("0", bitstrings(n-1))
>                 + appendInFront("1", bitstrings(n-1)))
> ###

And in fact you could even remove the if n== 2 line.
It works just fine using the appendInFRont function!

def bitstrings(n):
     if n == 0: return []
     if n == 1: return ["0", "1"]
     else:
         return (appendInFront("0", bitstrings(n-1))
                 + appendInFront("1", bitstrings(n-1)))
:-)

Alan G.




More information about the Tutor mailing list