To extract all (possibly non contiguous) sublists of length r from a list li, I wrote the function
def sublist(li, r):
output = list()
if r == 1:
return [ [element] for element in li ]
for firstelement in [1,len(li)-r+1]:
output += [ [li[firstelement-1]] + smallerlist for smallerlist in sublist(li[firstelement:],r-1) ]
return output
It does not seem to work:
sage: li = [20, 17, 33, 3001]
sage: sublist(li, 2)
[[20, 17], [20, 33], [20, 3001], [33, 3001]]
Notice that sublists starting with 17 are jumped over. The problem seems to be that the counter firstelement gets modified during the recursive call. Is there a simple way to fix this?
Umm, at a guess – are you trying to replicate combinations ?:
And you could use the “equivalent to:” section help write your own code: