I have four variables X1,X2,X3 and X4, which have the condition that in their sum they must always give me 1. That is, each variable represents a percentage of a total of 100%. But this percentage is based on a "step" , if I define my step as for example paso = 0.25
, I have less possible combinations (fewer rows), that if I define a smaller step like paso = 0.01
that will result in more rows.
Image to understand the idea:
In this case, the defined step is step = 0.25 , so as we can see there are 35 possible combinations, therefore 35 rows that can add 1 to me, without its value being repeated.
What I want to do is replicate this excel exercise in python, for which I started by doing the following:
def combinationSum(arr, sum):
ans = []
temp = []
# first do hashing nothing but set{}
# since set does not always sort
# removing the duplicates using Set and
# Sorting the List
arr = sorted(list(set(arr)))
findNumbers(ans, arr, temp, sum, 0)
return ans
def findNumbers(ans, arr, temp, sum, index):
if(sum == 0):
# Adding deep copy of list to ans
ans.append(list(temp))
return
# Iterate from index to len(arr) - 1
for i in range(index, len(arr)):
# checking that sum does not become negative
if(sum - arr[i]) >= 0:
# adding element which can contribute to
# sum
temp.append(arr[i])
findNumbers(ans, arr, temp, sum-arr[i], i)
# removing element from list (backtracking)
temp.remove(arr[i])
# Driver Code
arr = [2, 4, 6, 8]
sum = 8
ans = combinationSum(arr, sum)
# If result is empty, then
if len(ans) <= 0:
print("empty")
# print all combinations stored in ans
for i in range(len(ans)):
print("(", end=' ')
for j in range(len(ans[i])):
print(str(ans[i][j])+" ", end=' ')
print(")", end=' ')
In this code if as input we give:
[2, 4, 6, 8]
The output is:
( 2 2 2 2 ) ( 2 2 4 ) ( 2 6 ) ( 4 4 ) ( 8 )
This helped me to start, but I'm already stuck on how to continue, because all my output must have four values, for example, in the output (2 2 4) it must be like (2 2 4 0), also I need to implement the condition of the step with all the possible combinations based on it and all this in a Pandas dataframe.
Any idea how I could implement this?
Thanks in advance.