Ask Your Question
0

Generate all binary strings of length n [closed]

asked 2015-11-11 22:48:42 +0100

Pro gravatar image

I need to generate all binary strings of length 15 and then access individual bits. Is there some function for that? Thank You

edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by Pro
close date 2015-11-12 21:33:20.639853

2 Answers

Sort by ยป oldest newest most voted
3

answered 2015-11-11 23:04:23 +0100

tmonteil gravatar image

updated 2015-11-12 00:06:15 +0100

You can use words:

sage: W = Words(alphabet='01', length=15)
sage: W
Words of length 15 over {'0', '1'}

Then you can iterate over them, and access the i^th bit as follows:

sage: for w in W:
....:     print w, w[2]

If you want you bits to be integers, not strings, you can do:

sage: W = Words(alphabet=[0,1], length=15)
sage: W
Words of length 15 over {0, 1}

If you want to use only Python (not sage Words), you can use the itertools module:

sage: import itertools
sage: W = itertools.product([0,1], repeat=15)
sage: for w in W:
....:     print w, w[2]
edit flag offensive delete link more

Comments

Thank. Works perfectly

Pro gravatar imagePro ( 2015-11-12 21:33:42 +0100 )edit

Question Tools

1 follower

Stats

Asked: 2015-11-11 22:48:42 +0100

Seen: 4,509 times

Last updated: Nov 12 '15