获得所有可能的组合,得出总计

问题描述 投票:0回答:1

我需要知道如何改进这段代码,以便它向我显示所有可能的数字组合,这些数字相加得到我正在寻找的结果。

code

import itertools
lista=[95.95, 73.35, 78.85, 78.85, 22.85, 90.45, 64.15, 88.45, 37.12, 90.45, 37.12, 37.12, 95.95, 14.18, 78.85, 78.85, 64.15, 90.45, 90.45, 56.08, 66.75]

opcion= 0
valor=662.25
while opcion !=4:
    print(" 1- Ingresar el total: ")
    print(" 2- Ingresar sumandos: ")
    print(" 3- Modificar sumandos: ")
    print(" 4- salir: ")
    
    opcion=int(input())
    if opcion == 1:
        valor=float(input("digite el valor de la suma a la cual desea llegar: "))
    elif opcion == 2:
        numero=float(input("digite los sumandos: "))
        lista.append(numero)
        print(lista)
    elif opcion == 3:
        print(f"Estos son los valores que acaba de ingresar:\n{lista}\n\n\n")
        posicion=float(input("ingrese el valor que desea eliminar: "))
        lista.remove(posicion)
    elif opcion == 4: 
        break
# Generar todas las combinaciones posibles
combinations = []
for r in range(len(lista)):
    combinations += itertools.combinations(lista, r)

# Comprobar si la suma de cada combinación es igual a la suma objetivo
result = []
for combo in combinations:
    if sum(combo) == valor:
        result.append(combo)

# Mostrar las combinaciones encontradas
if result:
    for combo in result:
        print(combo)
else:
    print("no se encontraron resultados")

在这种情况下,当我运行程序时,它告诉我它没有找到任何解决方案,但它确实找到了,它是这样的: [22.85 , 90.45 , 88.45 , 90.45 , 37.12 , 95.95 , 90.45 , 90.45 , 56.08]

python combinations
1个回答
0
投票

您的问题(现在)是浮点舍入错误:

$ python
Python 3.8.10 (default, May 26 2023, 14:05:08) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [22.85 , 90.45 , 88.45 , 90.45 , 37.12 , 95.95 , 90.45 , 90.45 , 56.08]
>>> print(sum(a))
662.2500000000001

注意:这并不完全是

662.25
,因此您使用
==
的测试很可能会失败。

这不是 python 错误。相反,它是浮点运算在计算机上工作方式的结果。有两种方法可以解决这个问题:

  1. 进行范围测试;例如测试两个值之间的差异的绝对值是否小到可以接受。

  2. 使用(例如)

    decimal.Decimal
    进行算术运算。

© www.soinside.com 2019 - 2024. All rights reserved.