Предположим, в столбце «A» Excel есть отрицательные числа, такие как -1, -3, -6, -8 и положительное число 11. Теперь я хочу, чтобы Python нашел комбинацию этих отрицательных чисел, которые при сложении будут быть в точности равным 11, например -8 и -3, и их разница с положительным значением «нет» будет равна 0, и в то же время выделите ячейку с этими отрицательными числами и сохраните выходной файл Excel.
Приведенные выше цифры приведены только для примера.
Please Assist
**This is the code which i used but not getting the results I guess there is an issue in Logic applied **
import pandas as pd
import itertools
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
# Load the Excel file
input_file = 'input.xlsx'
output_file = 'output.xlsx'
df = pd.read_excel(input_file)
# Extract the numbers from column A
numbers = df['A'].tolist()
# Separate the positive number and negative numbers
positive_num = None
negative_nums = []
for num in numbers:
if isinstance(num, (int, float)):
if num > 0:
positive_num = num
elif num < 0:
negative_nums.append(num)
# Function to find the combinations
def find_combinations(nums, target):
for r in range(1, len(nums) + 1):
for subset in itertools.combinations(nums, r):
if sum(subset) == target:
return subset
return None
# Find the combination of negative numbers that sum to the positive number
combination = find_combinations(negative_nums, positive_num)
# Load the workbook and select the active sheet
wb = load_workbook(input_file)
ws = wb.active
# Highlight the numbers in the combination
if combination:
fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
for cell in ws['A']:
if cell.value in combination:
cell.fill = fill
# Save the modified file
wb.save(output_file)
print(f"The output file has been saved as {output_file}")
Подробнее здесь: https://stackoverflow.com/questions/785 ... ly-matches