NLP基础:动态规划练习
1. 连续子序列和的最大值
input = [-2, 11, -4, 13, -5, -2]
def max_sum_subseq(input):
"""
求解子序列的和的最大值
:param input:输入的实数组
:return :子序列和的最大值
"""
length = len(input)
dp = [0]*(length)#数组中的每个元素值代表到当前位置的和的最大值
dp[0] = input[0]#第一个元素赋值
for index in range(1, length):
dp[index] = max(input[index], dp[index - 1] + input[index])
return max(dp)
print(max_sum_subseq(input))
#运行结果
D:\Anaconda\python.exe "E:/project/dynamic programming/maximum value contiguous subseq.py"
20
Process finished with exit code 0
2. 最长递增序列(不一定连续)
input = [8, 1, 7, -2, 11, 13, 133, -2, 134, 138, 888]
def longest_increasing_subseq(input):
"""
求解子序列的和的最大值
:param input:输入的实数组
:return :递增序列的最大长度(不一定是连续的)
"""
length = len(input)
dp = [0]*(length)#数组中的每个元素值代表到当前位置递增序列长度
dp[0] = 1#第一个元素赋值
for index in range(1, length):
dp_tmp = [0]
for pre_index in range(index):
if input[index] > input[pre_index]:
dp_tmp.append(dp[pre_index])
else:
pass
dp[index] = max(dp_tmp) + 1
return max(dp)
print(longest_increasing_subseq(input))
#运行结果
D:\Anaconda\python.exe "E:/project/dynamic programming/longest_increasing_subseq.py"
8
Process finished with exit code 0
3. 凑硬币问题
coins = [1, 5, 10, 50, 100]
# num_coins = {}
def making_change(money):
"""
:param money: 输入的面额
:return :至少所需的硬币数量以及哪些硬币
"""
dp = [0]*(money+1) #每个值代表要得到相应值的硬币数,例如dp[10]代表得到10元所需的硬币数
dp[1] = 1
# parent = [None]*(money+1)
for target in range(1, money+1):#从1元开始
options = [x for x in coins if x <= target]#可选面额列表
tmp_lst = []
# previous = []
for option in options:
tmp_lst.append(dp[target - option])#将符合要求的暂存
# previous.append(option)
dp[target] = min(tmp_lst) + 1
# option_need = previous[tmp_lst.index(min(tmp_lst))]
# if option_need in num_coins:
# num_coins[option_need] += 1
# else:
# num_coins[option_need] = 1
# parent[target] = previous[tmp_lst.index(min(tmp_lst))]
#
# num_coins_sort = list(sorted(num_coins.items(), key=lambda x: x[1], reverse=False))
# res = 0
# res_tmp = []
# for coin, num in num_coins_sort:
# res += coin * num
# res_tmp.append((coin, num))
# if res >= money:
# break
# print(1)
return dp[money]
num_coin = making_change(110)
print(num_coin)
#测试结果
D:\Anaconda\python.exe "E:/project/dynamic programming/coins.py"
2
Process finished with exit code 0
4.总结
先写这么多吧,后面再增加其他的DP问题,还没解决如何返回递增序列具体是哪些、所需的硬币具体数量和面额是哪些。