I am trying to get every possible combination and permutation of adding one and two to reach a number. For example, you can get to 5 by adding 1 + 1 + 2
or 2 + 2 + 1
, etc.
objective:return a list of all lists made of 1's and 2's where the sum of the elements equals the parameter
my code won't work for 0,1, and 2 as pointed out
for example:
3: [1,1,1],[1,2],[2,1]
4: [1,1,1,1],[1,2,1],[2,1,1],[1,1,2],[2,2]
I have figured out a way of doing it, but it only works up till 7, as it won't find the 'middle' combination (not the most 1's or two's, just an average amount).
My function doesn't find any permutations, it just does the combinations.
def findsum(x):
numbers = []
numOfOnes= x - 2
numbers.append([1]*x) # all ones
numbers.append([1] * numOfOnes + [2]) #all ones and a two
if x % 2 == 0:
numOfTwos = int((x - 2)/2)
numbers.append([2]*(int(x/2))) # all twos
if x >= 6:
numbers.append([2] * numOfTwos+ [1,1]) #all twos and 2 ones
else:
numOfTwos = int((x - 1)/2)
numbers.append([2] * numOfTwos+ [1])
return numbers
Usage:
print(findsum(6))
# if number is greater that 7, won't get middle combination. Ex:
# [1,1,1,2,2] = 7 #doesn't have max 1's or 2's, , so won't be found in my algo
# [1,1,2,2,1,1] = 8 #doesn't have max 1's or 2's, so won't be found in my algo.