gpt4 book ai didi

python - 动态规划 : Number of ways of partitioning a set of numbers

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:08:58 25 4
gpt4 key购买 nike

<分区>

在阅读算法书时,我发现了以下练习。

Given a set of n elements, write an algorithm that finds number of ways of partitioning it. Example: When n = 2, there are 2 ways of partitioning the set(into two sets with one element, or into the original set and the empty set).

我没有使用算法,而是使用动态编程尝试了 python 代码。

def ways(n):
dp = [0]*(n+1),
sum = [0]*(n+1) ## declaring 2 arrays of n+1 size
dp[0] = 0
dp[1] = 1
sum[0] = 0
sum[1] = 1
lastcalc = 1 # last calculated var
for i in range (2,n):
if lastcalc < i/2 :
for j in range (lastcalc, i/2):
sum[j] = sum[j-1] + dp[j]
lastcalc = (i/2) # update the lastcalculated variable
dp[i] = sum[i/2]
return dp[n]

print(ways(2))

但是,代码将无法运行并给了我一个错误。

TypeError: 'tuple' object does not support item assignment

我的问题:我该如何解决这个问题?我可以说这段代码应用了动态规划吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com