suppose in “A” Column of excel there are negative numbers such as -1, -3,-6,-8 and a positive number 11 now i want python to find the combination of those negative numbers which if added together will be exactly equal to 11 like -8 and -3 and their difference with the positive no will be 0 and at the same time highlight the cell of those negative numbers as well and save the output excel file.
The above numbers are just for example
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}")
Shiv Sharma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.