fork download
  1. def subsets(n, k):
  2. assert k >= 0 and n >= 0
  3. if k == 0: # no students, all seats are empty
  4. yield '0'*n
  5. elif k == 1 and (n == 1 or n == 2): # the last student at the end of the row
  6. yield '1' + '0'*(n-1) # either '1' or '10'
  7. if n == 2: yield '01'
  8. elif n > 3*(k-1): # there are enough empty seats left for k students
  9. for s in subsets(n-3, k-1):
  10. yield '100' + s # place a student
  11. for s in subsets(n-1, k):
  12. yield '0' + s # add empty seat
  13.  
  14. def isvalid(a, n, k):
  15. if not isinstance(a, basestring):
  16. a = ''.join(a) # `a` is a list of '1', '0'
  17. return (len(a) == n and a.count('1') == k and a.count('0') == (n-k) and
  18. all(p not in a for p in ['11', '101']))
  19.  
  20.  
  21. n, k = 5, 2
  22. for s in subsets(n, k):
  23. assert isvalid(s, n, k), s
  24. print(s)
  25.  
Success #stdin #stdout 0.02s 6356KB
stdin
Standard input is empty
stdout
10010
10001
01001