[Tutor] Bit Strings [a recursive approach]

Gregor Lingl glingl at aon.at
Thu Oct 23 12:12:32 EDT 2003



Alan Gauld schrieb:

> ...
>
>>just write:
>>
>>###
>>def bitstrings(n):
>>...
>>
>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.
>  
>
May I supply another flavourof the recursive approach, which even 
doesn't need
appendInFront (but incorporagtes it itself)? It's nevertheless very compact:

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

 >>> bitstrings(3)
['000', '001', '010', '011', '100', '101', '110', '111']

Regards, Gregor

>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>




More information about the Tutor mailing list