Hướng dẫn python list disk partitions
Unlike my comments suggested, I was unable to quickly find an itertools based relatively fast solution! Edit: this is no longer quite true, I have a fairly short (but slow and unreadable) solution using itertools largely, see the end of the answer. This is what I got instead: The idea is that we find all the combinations of integers that add up to the length of the list, and then get lists with slices of that length. E.g. for a list of length 3, the combinations, or partitions, are (3), (2, 1), (1, 2) and (1, 1, 1). So we return the first 3 items of the list; the first 2 and then the next 1; the first 1 then the next 2 and the first 1, then the next 1, then the next 1. I got code for integer partioning from here. However, partition functions don't return all permutations of the partitions (i.e. for 3 it would just return (3), (2, 1) and (1, 1, 1). So we need to call Then all that remains is getting slices of the list the for the lengths in the tuple. E.g. My definition of that is this:
Now we just combine everything:
Also, you need to do Edit: your given output is unclear. I
presumed you wanted the function that I have given you, but your output also contains That is to say, I presume what you meant to give as output was this:
If in actual fact it was this:
Then you simply need to call Edit: Now to hold up to my promise of a short First we replace
Then from this answer we get our integer partitioning function:
This function actually gets all permutations of the integer partitions for us, so we don't need
anymore. However, it is much slower than what we had before, as it is recursive (and we are implementing it in Python). Then we just put it together:
Or less readable, but without the function definitions:
which is a function definition and two lines, so fairly close to what I originally stated (although much less readable and much slower)! (Functions called |