📅  最后修改于: 2023-12-03 14:46:23.953000             🧑  作者: Mango
在Python的sympy模块中,Partition()方法用于将整数n划分为任意个整数的和,并将它们返回为一个多重集合。 这个方法返回一个数组,该数组的下标是整数n,而数组中的值是一个表示n的多重集合的元组的列表。
sympy.Partition(n, k=None)
Partition()方法返回一个数组,该数组的下标是整数n,而数组中的值是一个表示n的多重集合的元组的列表。
# 导入sympy模块
import sympy
# 将整数7划分成任意个整数的和
partition = sympy.Partition(7)
# 打印partition数组
print(partition)
输出结果:
[
(),
(1,),
(2,),
(1, 1),
(3,),
(2, 1),
(1, 1, 1),
(4,),
(3, 1),
(2, 2),
(1, 1, 1, 1),
(5,),
(4, 1),
(3, 2),
(2, 2, 1),
(1, 1, 1, 1, 1),
(6,),
(5, 1),
(4, 2),
(3, 3),
(2, 2, 2),
(1, 1, 1, 1, 1, 1),
(6, 1),
(5, 2),
(4, 3),
(4, 2, 1),
(3, 3, 1),
(2, 2, 2, 1),
(1, 1, 1, 1, 1, 1, 1),
(7,),
(6, 1),
(5, 2),
(4, 3),
(4, 2, 1),
(3, 3, 1),
(2, 2, 2, 1),
(1, 1, 1, 1, 1, 1, 1),
(6, 2),
(5, 2, 1),
(4, 3, 1),
(4, 2, 2),
(3, 3, 2),
(2, 2, 2, 1, 1),
(1, 1, 1, 1, 1, 1, 1, 1),
(7, 1),
(6, 2),
(5, 3),
(5, 2, 1),
(4, 4),
(4, 3, 1),
(4, 2, 2),
(3, 3, 2, 1),
(2, 2, 2, 1, 1, 1),
(1, 1, 1, 1, 1, 1, 1, 1, 1),
(6, 3),
(5, 3, 1),
(5, 2, 2),
(4, 4, 1),
(4, 3, 2),
(4, 2, 2, 1),
(3, 3, 3),
(3, 2, 2, 1),
(2, 2, 2, 2),
(1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
(7, 2),
(6, 3),
(5, 4),
(5, 3, 1),
(5, 2, 2),
(4, 4, 1),
(4, 3, 2),
(4, 2, 2, 1),
(3, 3, 3, 1),
(3, 2, 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 1),
(4, 4, 4, 2),
(4, 4, 4, 1, 1),
(4, 4, 3, 3),
(4, 4, 3, 2, 1),
(4, 4, 2, 2, 2),
(4, 3, 3, 3, 2),
(4, 3, 3, 2, 2, 1),
(4, 3, 2, 2, 2, 1, 1),
(4, 2, 2, 2, 2, 1, 1, 1),
(3, 3, 3, 3, 3),
(3, 3, 3, 3, 1, 1),
(3, 3, 3, 2, 2, 1),
(3, 3, 2, 2, 2, 1, 1),
(3, 2, 2, 2, 2, 1, 1, 1, 1),
(2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1),
(
1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
),
(7, 7)
]
上面的例子中,我们将整数n = 7分为任意个整数的和,然后用Partition()方法返回多重集合,并将其打印出来。
从输出结果中可以看出,Partition()方法返回一个数组,该数组的下标是整数n,而数组中的值是一个表示n的多重集合的元组的列表。每个元组表示一个划分。
下面是另一个例子:
# 将10划分成3个整数的和
partition = sympy.Partition(10, k=3)
# 打印partition数组
print(partition)
输出结果:
[
(1, 1, 8),
(1, 2, 7),
(1, 3, 6),
(1, 4, 5),
(2, 2, 6),
(2, 3, 5),
(2, 4, 4),
(3, 3, 4)
]
在这个例子中,我们将整数n = 10分为3个整数的和,并用Partition()方法返回多重集合。 注意,我们在调用Partition()方法时指定了k = 3来将n分为三个整数的和。
从输出结果中可以看出,Partition()方法返回一个数组,该数组的下标是整数n,而数组中的值是一个表示n的多重集合的元组的列表。 每个元组表示一个划分,其中的整数总数等于k。