Python Lab · Experiment 22
Generate all binary strings of n bits using recursion
PythonWeek 4JNTUH R22 · CS206ES
Aim
To write a recursive Python function that generates all binary strings of length n, and a program that reads n and prints every string and the total count.
Algorithm
- Read n. If n is less than 1, print a message and stop.
- Define the recursive function binary_strings(n).
- Base case: if n is 0, return a list holding only the empty string.
- Otherwise, get all strings of length n − 1 by calling binary_strings(n − 1).
- Make a new list: first each shorter string with "0" in front, then each shorter string with "1" in front.
- Return the new list.
- Print every string of the list and the count, which is 2ⁿ.
Program
def binary_strings(n):
"""Return a list of all binary strings with n bits."""
if n == 0:
return [""] # one string of length 0: the empty string
shorter = binary_strings(n - 1)
result = []
for s in shorter:
result.append("0" + s)
for s in shorter:
result.append("1" + s)
return result
n = int(input("Enter the number of bits n: "))
if n < 1:
print("n must be at least 1")
else:
strings = binary_strings(n)
print(f"All {n}-bit binary strings:")
for s in strings:
print(s)
print("Total:", len(strings))Output
n = 3
Enter the number of bits n: 3
All 3-bit binary strings:
000
001
010
011
100
101
110
111
Total: 8n = 2
Enter the number of bits n: 2
All 2-bit binary strings:
00
01
10
11
Total: 4Recorded by running this exact program. Typed input appears after each prompt.
How it works
Every n-bit string is either "0" followed by an (n − 1)-bit string, or "1" followed by an (n − 1)-bit string. That is the idea behind the recursion. Putting all the "0" strings first gives the strings in increasing order, like counting in binary from 0 to 2ⁿ − 1.
The count doubles with each extra bit, so there are 2ⁿ strings: 8 for n = 3, and over a million for n = 20. Keep n small when printing.
Another common recursive version builds the string as it goes and prints it at the end:
def generate(n, prefix=""):
if n == 0:
print(prefix)
return
generate(n - 1, prefix + "0")
generate(n - 1, prefix + "1")Common mistakes
Leaving out the base case. The function then calls itself with n − 1, n − 2, … forever, until Python raises
RecursionError.Returning an empty list
[]for n = 0 instead of[""]. Nothing can be added in front of an empty list, so every result comes out empty.Calling
binary_strings(n - 1)twice, once for each loop. It gives the right answer but does the same work twice; store the result in a variable.Treating the strings as numbers.
int("011")is 11, not 3, and loses the leading zero. Keep them as strings.
Viva questions
Try to answer each one aloud before you open it.
What is recursion?
A function calling itself to solve a smaller version of the same problem. It needs a base case that is answered directly, so the calls stop.
What is the base case in this program?
n = 0. There is exactly one binary string of length 0, the empty string, so the function returns
[""].How many binary strings of length n are there?
2ⁿ, because each of the n positions can be 0 or 1 independently.
What happens if a recursive function has no base case?
It keeps calling itself until Python's recursion limit (about 1000 calls by default) is reached and a
RecursionErroris raised.How can you get the same strings without recursion?
Loop i from 0 to 2ⁿ − 1 and print i in binary, padded with zeros to n digits:
format(i, "b").zfill(n). For n = 3, i = 1 gives"001"and i = 5 gives"101".