[Tutor] Bit Strings
Timothy M. Brauch
tbrauch at mindless.com
Wed Oct 22 00:07:36 EDT 2003
There has to be an easy way to do this that I am just not seeing. I am
trying to create all bit strings of length n. Right now my code is as
follows:
bitStrings = []
for a0 in [0,1]:
for a1 in [0,1]:
for a2 in [0,1]:
oneString = str(a0)+str(a1)+str(a2)
bitStrings.append(oneString)
print bitStrings
I know this is ugly and when I need longer strings, say n = 10, the code
gets way too repetitive with 10 nested for loops. Surely there is an easier
way to do this, but I just can't figure it out. I have a function that will
generate the above functions, but it is uglier and probably way not the
correct way to go about this.
def generator(n):
tb = " "
stringMaker = ""
print "bitStrings = []"
for i in xrange(0,n+1):
print i*tb + "for a"+str(i)+" in [0,1]:"
stringMaker = stringMaker + "str"+chr(40)+"a"+str(i)+chr(41)+chr(43)
stringMaker = stringMaker[:-1] #strip the last chr(43)
print (i+1)*tb + "oneString = "+stringMaker
print (i+1)*tb + "bitStrings.append(oneString)"
print "print bitStrings"
Any suggestions?
- Tim
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.528 / Virus Database: 324 - Release Date: 10/17/2003
More information about the Tutor
mailing list