Python计算数组内任意元素的和为指定值的组合
给定一个有若干原素的数组,要求从数组内找到一个组合,使其和等于指定的值,下面的python代码使用递归方式实现,给定的数组是两位小数点的浮点数,所以先将浮点数转换成整数后再进行处理。
""" @Author:dfugo(pidancode.com) @Date:2022/12/10 @Description:计算数组内任意元素的和为指定值的组合 """ class Cal(object): n = 0 def get_arr(self, lst, value): """从数组lst中任意组合元素的和为value""" self.n = self.n + 1 # 计算data的总和 arr_sum = sum(lst) print(f'遍历第{self.n}次,和为:{arr_sum}') # 如果总和小于value,直接返回空数组 if arr_sum < value: return [] # 如果总和等于value,直接返回data if arr_sum == value: return lst # 如果总和大于value,进行递归计算 if arr_sum > value: # 从data中随机取出一个元素 for i in range(len(lst)): # 从data中删除取出的元素 t = lst.pop(i) # 递归计算 result = self.get_arr(lst, value) # 如果递归计算结果不为空,直接返回结果 if result: return result # 如果递归计算结果为空,将删除的元素重新加入lst lst.insert(i, t) # 如果data中所有元素都遍历完毕,且递归计算结果为空,返回空数组 return [] if __name__ == '__main__': data = [ 10185, 1199.21, 5599.80, 270, 1700, 810, 849.15, 849.15, 754, 168.30, 86.40, 2.05, 93.29, 60, 190.95, 90.8, 60, 89.28, 95.84, 55.72, 90.28, 75.73, 161.15, 74.04, 15.14, 79.26, 92.87, 90.63, 15.27, 15.90, 7.4, 8.59, 87.60, 9.50, 38.69, 14.88, 1.18, 90.33, 31.82, 1121.74, 210.18, 475.8, 10.2, 14.40, 86.72, 0.29, 28.84, 14.88, 89.59, 0.01, 1.39, 0.09 ] # 将数据都转换成整数后计算 data = [round(item * 100) for item in data] cal = Cal() result = cal.get_arr(lst=data, value=2200000) sum_of_result = sum(result) / 100 result = [item / 100 for item in result] print(f'sum of result is {sum_of_result}, result is {result}')
输出结果如下:
sum of result is 22000, result is [10185.0, 5599.8, 849.15, 849.15, 754.0, 93.29, 60.0, 190.95, 90.8, 60.0, 89.28, 95.84, 55.72, 90.28, 75.73, 161.15, 74.04, 15.14, 79.26, 92.87, 90.63, 15.9, 7.4, 8.59, 87.6, 38.69, 14.88, 90.33, 31.82, 1121.74, 210.18, 475.8, 10.19, 14.4, 86.72, 0.28, 28.84, 14.88, 89.59, 0.09]
相关文章