Splitting an integer into smaller integers of defined sizes in Python

时间:2016-04-15 14:58:45

标签: python

I need to split an integer value of arbitrary size into smaller integers (chunks), and do it in the most efficient way. The chunks sizes I have are 1, 2, 3, 4, 6, 8, 16.

Let's say I need to split an integer 45: The chunks I would have would be: 16, 16, 8, 4, 1. How would I write a Python function to do that for me?

2 个答案:

答案 0 :(得分:4)

鉴于你说的话,一个贪婪的解决方案将起作用,这是一个有效的解决方案:

def split_number(n, sizes):
    sizes = sorted(sizes, reverse=True)
    ret = {}

    for size in sizes:
        if size <= n:
            ret[size], n = divmod(n, size)

    return ret

print split_number(45, [1, 2, 3, 4, 6, 8, 16])

给定任意大小的问题称为背包问题,即NP-Hard

答案 1 :(得分:1)

You can convert the given number to its binary equivalent and reconvert the binary term by term to decimal. This way 45 = 32 + 8 + 4 + 1. Since 32 is not allowed you just split it to 16+16

A code is given below :

quotient = int(input("Enter a number: "))
count=0
result=[]
while quotient != 0:
    remainder = quotient%2
    quotient = quotient//2   
    count +=1
    result.append(remainder)
n=0
while n<len(result):
    chunk=result[n]*2**(n)
    if chunk <=16:
        print (chunk,end=' ')
    else:
        q=chunk/16
        for times in range(int(q)):
            print (16,end=' ')
    n=n+1
print('\n')

Is this what you wanted?