import numpy def find_closest_cell(cell_capacities, target_capacity): closest = min(cell_capacities, key=lambda x: x-target_capacity) cell_capacities.remove(closest) return closest def split_cells(cell_capacities, series_count): # get use the average cell capacity and the number of cells in series/parallel to get a target capacity average_cell_capacity = numpy.mean(cell_capacities) std_dev = numpy.std(cell_capacities) cells_in_parallel = int(len(cell_capacities)/series_count) target_bank_capacity = average_cell_capacity * cells_in_parallel print(f'Average Capacity: {average_cell_capacity}\n' f'Standard Deviation: {std_dev}\n' f'Target Bank Capacity: {target_bank_capacity}\n') # create a list of the banks battery_banks = [] # sort the cells cell_capacities.sort(reverse=True) for bank_num in range(0, series_count): # Add the highest capacity cells to different banks battery_banks.append([cell_capacities.pop(bank_num)]) # search for cells with the closest value to get to the average of the cell banks # subtract 1 since 1 cell has already been added for call_num in range(0, cells_in_parallel - 1): for bank in battery_banks: # get the target average (add one, since we are adding a cell) current_target_bank_capacity = average_cell_capacity * (len(bank) + 1) # get the current capacity current_bank_capacity = sum(bank) target_cell_capacity = current_target_bank_capacity - current_bank_capacity # find the closest cell and add it to the bank bank.append(find_closest_cell(cell_capacities, target_cell_capacity)) return battery_banks if __name__ == '__main__': battery_caps = [] with open('C:\\Users\\Chris\\Documents\\Projects\\Telescope\\Batteries capacities.txt') as battery_list: battery_caps = [int(capacity) for capacity in battery_list.read().splitlines()] battery_bank_cells = split_cells(battery_caps, 4) bank_caps = [sum(b) for b in battery_bank_cells] mean_bank_capacity = numpy.mean(bank_caps) std_bank_deviation = numpy.std(bank_caps) print(f'Battery Bank Capacities: {bank_caps}\n' f'\n' f'Mean bank Capacity: {mean_bank_capacity}\n' f'Standard Deviation: {std_bank_deviation}\n' f'Percentage Variance: {100*std_bank_deviation/mean_bank_capacity:.4f}%\n' f'\n') for i in range(0, len(battery_bank_cells)): print(f'-----------------------------------------------------------------------------------\n' f'Bank {i +1}:') for c in battery_bank_cells[i]: print(f' {c}')