Search code examples
pythonmathdd

Split integer into equal chunks


What is the most efficient and reliable way in Python to split sectors up like this:

number: 101 (may vary of course) chunk1: 1 to 30 chunk2: 31 to 61 chunk3: 62 to 92 chunk4: 93 to 101

Flow: copy sectors 1 to 30 skip sectors in chunk 1 and copy 30 sectors starting from sector 31. and so on...

I have this solved in a "manual" way using modules and basic math but there's got to be a function for this?

Thank you.


Solution

  • I assume that you will have number in a list format. So, in this case if you want very specific format of cluster of number sequence and you know where it should separate then using indexing is the best way as it will have less time complexity. So,you can always create a small code and make it a function to use repeatedly. Something like below:

    def sectors(num_seq,chunk_size=30):
        ...:     import numpy as np
        ...:     sectors = int(np.ceil(len(num_seq)/float(chunk_size))) #create number of sectors
        ...:     for i in range(sectors):
        ...:         if i < (sectors - 1):
        ...:             print num_seq[(chunk_size*i):(chunk_size*(i+1))] #All will chunk equal size except the last one.
        ...:         else:
        ...:             print num_seq[(chunk_size*i):] #Takes rest at the end. 
    

    Now, every time you want similar thing you can reuse it and it is efficient as you are defining list index value instead of searching through it.

    Here is the output:

    x = range(1,101)   
    print sectors(x)
        [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
        [31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]
        [61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
        [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
    

    Please let me know if this meets your requirement.