### Thread: Recursive code to print samples size of size n

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2012
Posts
15
Rep Power
0

#### Recursive code to print samples size of size n

Hey guys, I need to write code that will take a list and print samples of size n with replacement, recursively. I have written a program that will print samples of size n from a list, but now how do I do it recursively?

Here is my code for the program done not recursively:
Code:
```S = []
L = ['a','b','c','d']
N = len(L)
for k1 in range(N):
if L[k1]:
S.append(L[k1])
for k2 in range(N):
S.append(L[k2])
for k3 in range(N):
S.append(L[k3])
print S
L[k3] = S.pop()
L[k2] = S.pop()
L[k1] = S.pop()```
So this code will print [a,a,a], [a,a,b], [a,a,c], [a,b,a],..., [d,d,c], [d,d,d].
2. An easy way to solve this sort of problem: learn lisp, find a lisp code for it. Translation to python is straightforward. I didn't need to resort to that, and came up with:
Code:
```def f(A,B,N):
if not N:
print(B)
else:
for C in A:
f(A,B+C,N-1)

print('')
f('abcd','',2)
print('')
f('abcd','',3)
print('')
f('abcd','',5)```