Is there any python module to divide a number N into 3 parts such that sum of that parts equal to N? or how to do that?

Question:

  • I tried gcd But didn’t work.
  • n = 18 # given number n
  • x = 3 # 3 parts or x number of part

OUTPUT ->

(1,9,8),(2,8,8),(3,6,9)……

Asked By: Ashiq

||

Answers:

i don’t really understand what your asking but this could work:

n = input("pick a number for n: ")
print(str(n), "divide by 3 is", str(n/3))

answer:

pick a number for n: 6
6 divide by 3 is 2

also there is a module called math

Answered By: person
l=[]
for i in range(1, 19):
    for j in range(1, 19):
        for k in range(1, 19):
            if i + j + k == 18:
                l.append((i,j,k))

#output
[(1, 1, 16), (1, 2, 15), (1, 3, 14), (1, 4, 13), (1, 5, 12), (1, 6, 11), (1, 7, 10), (1, 8, 9), (1, 9, 8), (1, 10, 7), (1, 11, 6), (1, 12, 5), (1, 13, 4), (1, 14, 3), (1, 15, 2), (1, 16, 1), (2, 1, 15), (2, 2, 14), (2, 3, 13), (2, 4, 12), (2, 5, 11), (2, 6, 10), (2, 7, 9), (2, 8, 8), (2, 9, 7), (2, 10, 6), (2, 11, 5), (2, 12, 4), (2, 13, 3), (2, 14, 2), (2, 15, 1), (3, 1, 14), (3, 2, 13), (3, 3, 12), (3, 4, 11), (3, 5, 10), (3, 6, 9), (3, 7, 8), (3, 8, 7), (3, 9, 6), (3, 10, 5), (3, 11, 4), (3, 12, 3), (3, 13, 2), (3, 14, 1), (4, 1, 13), (4, 2, 12), (4, 3, 11), (4, 4, 10), (4, 5, 9), (4, 6, 8), (4, 7, 7), (4, 8, 6), (4, 9, 5), (4, 10, 4), (4, 11, 3), (4, 12, 2), (4, 13, 1), (5, 1, 12), (5, 2, 11), (5, 3, 10), (5, 4, 9), (5, 5, 8), (5, 6, 7), (5, 7, 6), (5, 8, 5), (5, 9, 4), (5, 10, 3), (5, 11, 2), (5, 12, 1), (6, 1, 11), (6, 2, 10), (6, 3, 9), (6, 4, 8), (6, 5, 7), (6, 6, 6), (6, 7, 5), (6, 8, 4), (6, 9, 3), (6, 10, 2), (6, 11, 1), (7, 1, 10), (7, 2, 9), (7, 3, 8), (7, 4, 7), (7, 5, 6), (7, 6, 5), (7, 7, 4), (7, 8, 3), (7, 9, 2), (7, 10, 1), (8, 1, 9), (8, 2, 8), (8, 3, 7), (8, 4, 6), (8, 5, 5), (8, 6, 4), (8, 7, 3), (8, 8, 2), (8, 9, 1), (9, 1, 8), (9, 2, 7), (9, 3, 6), (9, 4, 5), (9, 5, 4), (9, 6, 3), (9, 7, 2), (9, 8, 1), (10, 1, 7), (10, 2, 6), (10, 3, 5), (10, 4, 4), (10, 5, 3), (10, 6, 2), (10, 7, 1), (11, 1, 6), (11, 2, 5), (11, 3, 4), (11, 4, 3), (11, 5, 2), (11, 6, 1), (12, 1, 5), (12, 2, 4), (12, 3, 3), (12, 4, 2), (12, 5, 1), (13, 1, 4), (13, 2, 3), (13, 3, 2), (13, 4, 1), (14, 1, 3), (14, 2, 2), (14, 3, 1), (15, 1, 2), (15, 2, 1), (16, 1, 1)]
Answered By: Talha Tayyab

Have a look to the itertools library. Use product to get a powerset-like output and filter by a condition.

import itertools as it

n = 4
partitions = 3

combs = [comb for comb in it.product(range(n), repeat=partitions) if sum(comb) == n]
print(*combs, sep='n')

Remark: if 0 is not desired change the "list" with range(1, n+1)

Answered By: cards
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.