The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages
> Python Programming
|
Recursive code to print samples size of size n
Discuss Recursive code to print samples size of size n in the Python Programming forum on Dev Shed. Recursive code to print samples size of size n Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

September 23rd, 2012, 01:50 PM
|
|
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].
|

September 23rd, 2012, 07:36 PM
|
 |
Contributing User
|
|
|
|
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!
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|