python - 浮点值的子集总和不起作用

标签 python algorithm pandas numpy

我编写了计算子集总和的代码,它对于整数值来说就像一个魅力,但对于浮点值它没有给出结果。

代码:

import numpy as np
array = np.array([15,1,4,6,3,10,4.2])
num = 8.2

def subsetsum(array,num):

    if num == 0 or num < 1:
        return None
    elif len(array) == 0:
        return None
    else:
        if array[0] == num:
            return [array[0]]
        else:
            with_v = subsetsum(array[1:],(num - array[0])) 
            if with_v:
                return [array[0]] + with_v
            else:
                return subsetsum(array[1:],num)

print('\nList of Values : ',array)
print('\nSum Desired : ',num)
print('\nValues that add up to sum : ',subsetsum(array,num))

整数值的输出

List of Values :  [15  1  4  6  3 10  4]

Sum Desired :  8

Values that add up to sum :  [1, 4, 3]

浮点值的输出

List of Values :  [ 15.    1.    4.    6.    3.   10.    4.2]

Sum Desired :  8.2

Values that add up to sum :  None

如何使用浮点值?

最佳答案

那么你可以简单地使用 np.isclose 考虑 float 点数比较。因此,要解决您的问题,请将相等比较替换为: array[0] == num与:np.isclose(array[0], num) .

同样,您可能希望在开始时进行类似的编辑来修复:num == 0

关于python - 浮点值的子集总和不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41320257/

相关文章:

python - 调用从方法返回的对象方法作为方法变量

algorithm - 雅可比法的两种算法 : why the time change?

Python:没有得到列表的最长公共(public)子序列的长度

python - 如何从 pandas 列中的列表中提取元素并将它们附加到集合中

python - 将 Pandas 数据框处理成 fiddle 图

python - pandas 特定月份的平均值

python - flask Restful : how to give multiple arguments to get methhod of any Api using flask restful?

python - python selenium 驱动程序中的 "Message: unknown error: cannot focus element"

python - 将 json 数组中的键追加(映射)到另一个子数组

查找图中哈密顿路径数的算法