Advanced · Recursion · 161 of 264
All binary strings
Print every string of 0s and 1s of length n, in increasing order, using recursion.
Input: n (1 to 8). Output: the strings, one per line.
Examples
Input
2
Output
00 01 10 11
Input
1
Output
0 1
One more test checks other inputs when you press Check.
Stuck? The idea behind recursion
A recursive function calls itself on a smaller version of the problem, until it reaches a case small enough to answer directly (the base case).
Trust the smaller call to be right, and only work out how to build this answer from it.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))Watch for: Without a base case, or if the problem doesn't get smaller, it never stops: Python gives up with a RecursionError.