Python的整数分割与给定的k个划分 [英] Python Integer Partitioning with given k partitions

查看:488
本文介绍了Python的整数分割与给定的k个划分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图寻找或开发整数分割code为Python。

I'm trying to find or develop Integer Partitioning code for Python.

仅供参考,整数分区重新presenting一个给定的整数n为整数小于n的总和。例如,一个整数5可以是pssed作为当然$ P $ 4 + 1 = 3 + 2 = 3 + 1 + 1 = 2 + 2 + 1 = 2 + 1 + 1 + 1 = 1 + 1 + 1 + 1 + 1

FYI, Integer Partitioning is representing a given integer n as a sum of integers smaller than n. For example, an integer 5 can be expressed as 4 + 1 = 3 + 2 = 3 + 1 + 1 = 2 + 2 + 1 = 2 + 1 + 1 + 1 = 1 + 1 + 1 + 1 + 1

我已经找到了一些这种解决方案。 http://homepages.ed.ac.uk/jkellehe/partitions.php HTTP://$c$c.activestate.com /食谱/ 218332发电机换整数分区/

I've found a number of solutions for this. http://homepages.ed.ac.uk/jkellehe/partitions.php and http://code.activestate.com/recipes/218332-generator-for-integer-partitions/

不过,我真正想要的是限制分区数量。

However, what I really want is to restrict the number of partitions.

说,#分区的 K = 2,一个程序只需要出示 5 = 4 + 1 = 3 + 2

Say, # of partition k = 2, a program only need to show 5 = 4 + 1 = 3 + 2,

如果 K = 3, 5 = 3 + 1 + 1 = 2 + 2 + 1

推荐答案

我已经写了一台发电机的解决方案

I've written a generator solution

def partitionfunc(n,k,l=1):
    '''n is the integer to partition, k is the length of partitions, l is the min partition element size'''
    if k < 1:
        raise StopIteration
    if k == 1:
        if n >= l:
            yield (n,)
        raise StopIteration
    for i in range(l,n+1):
        for result in partitionfunc(n-i,k-1,i):
            yield (i,)+result

这会生成 N 的所有分区长度 K 与为了每一个是至少到最大。

This generates all the partitions of n with length k with each one being in order of least to greatest.

只是一个快速的注意,通过 CPROFILE ,看来使用生成方法比使用falsetru的直接方法,使用测试功能更快拉姆达X,Y:列表(partitionfunc(X,Y))。在测试运行 N = 50,K-5 ,我的code跑到0.019秒相较于2.612秒直接的方法。

Just a quick note: Via cProfile, it appears that using the generator method is much faster than using falsetru's direct method, using the test function lambda x,y: list(partitionfunc(x,y)). On a test run of n=50,k-5, my code ran in .019 seconds vs the 2.612 seconds of the direct method.

这篇关于Python的整数分割与给定的k个划分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆