Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
September 23rd, 2012, 02:50 PM
 norm850
Registered User

Join Date: Sep 2012
Posts: 15
Time spent in forums: 4 h 13 m 33 sec
Reputation 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
September 23rd, 2012, 08:36 PM
 b49P23TIvg
Contributing User

Join Date: Aug 2011
Posts: 4,140
Time spent in forums: 1 Month 3 Weeks 2 Days 7 h 17 m 40 sec
Reputation Power: 455
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)```
__________________
[code]Code tags[/code] are essential for python code!

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Recursive code to print samples size of size n