Skip to content

Instantly share code, notes, and snippets.

@kflu
Created June 27, 2012 02:15
Show Gist options
  • Save kflu/3000889 to your computer and use it in GitHub Desktop.
Save kflu/3000889 to your computer and use it in GitHub Desktop.
n choose k
def C(S,k):
'''Choose k elements from set S.'''
assert len(S) >= k
if k==0:
yield set()
S1 = S.copy()
for s in S:
S1.remove(s)
if len(S1) >= k-1:
for c in C(S1, k-1):
yield set([s]) | c
for c in C(set('abcd'), 0):
print ''.join(c)
@kflu
Copy link
Author

kflu commented Jun 27, 2012

The problem with revision 785674 is that the argument S gets changed (removing elements from it) by all levels of recursions. Since S is passed by reference, it's changed by a deeper level of recursion unintentionally.

def caller(lst):
    print "before calling callee:", lst
    callee(lst)
    print "after  calling callee:", lst

def callee(lst):
    del lst[-1]

caller([1,2,3])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment