# Generate all binary strings of length n [closed]

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

Generate all binary strings of length n [closed]

close date 2015-11-12 14:33:20.639853

add a comment

2

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]
```

Asked: **
2015-11-11 15:48:42 -0600
**

Seen: **2,221 times**

Last updated: **Nov 11 '15**

How to make a function of 'fname' that produce a file named 'fname'

Define vector valued function of a vector of symbolic variables?

Can sage compute the inverse of a function?

Is there a command to find the place of an element in an array?

Save plot in SVG with plain text strings

How do I define a piecewise function?

Display x-intercept of a plot, involving x raised to the 3rd power.

Copyright Sage, 2010. Some rights reserved under creative commons license. Content on this site is licensed under a Creative Commons Attribution Share Alike 3.0 license.