An algorithm for randomly generating integer partitions of a particular length, in Python?

后端 未结 3 1536
没有蜡笔的小新
没有蜡笔的小新 2021-01-05 10:58

I\'ve been using the random_element() function provided by SAGE to generate random integer partitions for a given integer (N) that are a particular

3条回答
  •  没有蜡笔的小新
    2021-01-05 11:35

    I ran into a similar problem when I was trying to calculate the probability of the strong birthday problem.

    First off, the partition function explodes when given only modest amount of numbers. You'll be returning a LOT of information. No matter which method you're using N = 10000 and S = 300 will generate ridiculous amounts of data. It will be slow. Chances are any pure python implementation you use will be equally slow or slower. Look to making a CModule.

    If you want to try python the approach I took as a combination of itertools and generators to keep memory usage down. I don't seem to have my code handy anymore, but here's a good impementation:

    http://wordaligned.org/articles/partitioning-with-python

    EDIT:

    Found my code:

    def partition(a, b=-1, limit=365):
      if (b == -1):
        b = a
      if (a == 2 or a == 3):
        if (b >= a and limit):
          yield [a]
        else:
          return
      elif (a > 3):
        if (a <= b):
          yield [a]
        c = 0
        if b > a-2:
          c = a-2
        else:
          c = b
        for i in xrange(c, 1, -1):
          if (limit):
            for j in partition(a-i, i, limit-1):
              yield [i] + j
    

提交回复
热议问题