I had to write a code for finding all non-empty sublists partitionings of a list:
def f(s):
if s:
for j in range(1,len(s)+1):
for p in f(s[j:]):
yield [s[:j]]+p
else:
yield []
I managed to shorten it (for Python 3.4+) to:
def f(s, p=[]):
if s:
for j in range(1,len(s)+1):
yield from f(s[j:],p+[s[:j]])
else:
yield p
using yield from and an accumulator argument p
(prefix).
Any suggestions on how to shorten it even more?
Example output:
>>> for p in f([1,2,3,4]): print(p)
...
[[1], [2], [3], [4]]
[[1], [2], [3, 4]]
[[1], [2, 3], [4]]
[[1], [2, 3, 4]]
[[1, 2], [3], [4]]
[[1, 2], [3, 4]]
[[1, 2, 3], [4]]
[[1, 2, 3, 4]]
>>>