Search code examples
pythonlistloopsoptimization

Python Creating chunks of val from given cap number


I am creating a list of a certain value given a cap number and I can do this using the following. I am just wondering if there is a better/shorter/faster way to do this.

cap = 93
chunkSize = 10
chunks = []
while cap > 0: 
    val = chunkSize if cap / chunkSize >= 1 else cap
    chunks.append(val)
    cap -= val

for i, q in enumerate(chunks):
    print(i, q)

And the expected and correct output is -

0 10
1 10
2 10
3 10
4 10
5 10
6 10
7 10
8 10
9 3

If there is some fancy way to do this, please reply.

I already have a working solution.


Solution

  • As noted by viggo, just calculate how many whole chunks you need. The difference is only that you need to check if the last chunk is not zero:

    # divmod: same as whole_chunks, last_chunk = cap // chunk_size, cap % chunk_size
    whole_chunks, last_chunk = divmod(cap, chunk_size)
    chunks = [chunk_size] * whole_chunks
    if last_chunk:
        chunks.append(last_chunk)