Monday, November 12, 2018

Q11:Cut me in Pieces but in The Way I Like

Question 11:
We need a function (for commercial purposes) that may perform integer partitions with some constraints. The function should select how many elements each partition should have. The function should discard some "forbidden" values in each partition. So, create part_const(), that receives three arguments. part_const((1), (2), (3))

(1) - The integer to be partitioned

(2) - The number of elements that each partition should have

(3) - The "forbidden" element that cannot appear in any partition
part_const() should output the amount of different integer partitions with the constraints required.

Let's see some cases:

part_const(10, 3, 2) ------> 4

/// we may have a total of 8 partitions of three elements (of course, the sum of the elements of each partition should be equal 10) :
[1, 1, 8], [1, 2, 7], [1, 3, 6], [1, 4, 5], [2, 2, 6], [2, 3, 5], [2, 4, 4], [3, 3, 4]

but 2 is the forbidden element, so we have to discard [1, 2, 7], [2, 2, 6], [2, 3, 5] and [2, 4, 4]

So the obtained partitions of three elements without having 2 in them are:
[1, 1, 8], [1, 3, 6], [1, 4, 5] and [3, 3, 4] (4 partitions)///
part_const() should have a particular feature:

if we introduce 0 as the forbidden element, we will obtain the total amount of partitions with the constrained number of elements.

In fact,

part_const(10, 3, 0) ------> 8 # The same eight partitions that we saw above.
Enjoy it and happy coding!!

3 comments:

  1. Hi jeevitha,

    is there any number limit for every elements in the sequence output like all numbers should be btwn 0-9 . ??

    [1, 1, 8], [1, 2, 7], [1, 3, 6], [1, 4, 5], [2, 2, 6], [2, 3, 5], [2, 4, 4], [3, 3, 4] - here every element in the lists are btwn 0-9. or it can be like [1,1,10] , [2,11,12]. please clarify.

    ReplyDelete
  2. There is no limit for elements. In the given example sum of three element s should be equal to 10. so numbers between 0-9 are used. if the number(to be partitioned) is greater then we can use numbers > 9 also.

    ReplyDelete
  3. from itertools import combinations_with_replacement
    def part_const(n, k, num):
    partitions = [i for i in list(combinations_with_replacement(range(1,n), k)) if sum(i)==n]
    if num==0:
    return len(partitions)
    else:
    return len([i for i in partitions if num not in i])
    print(part_const(10,3,2))

    ReplyDelete