Find combinations of one and two that add to a number - python-3.x

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.

What you're after are called integer compositions--specifically, compositions that only include 1 and 2.
Because this problem is related to the Fibonacci sequence, it stands to reason that a possible solution would be structurally similar to a Fibonacci algorithm. Here's a recursive version:
def f_rec(n):
assert n >= 0
if n == 0:
return [[]]
elif n == 1:
return [[1]]
else:
return [[1] + composition for composition in f_rec(n - 1)] \
+ [[2] + composition for composition in f_rec(n - 2)]
Explanation: let F(n) = all the compositions of n consisting of only 1's and 2's. Every composition must begin with a 1 or 2.
If a composition of n begins with a 1, then it must be followed by a composition of n - 1. If it begins with a 2, then it must be followed by a composition of n - 2. Hence, all the compositions of n are either 1 followed by all the compositions of n - 1, or 2 followed by all the compositions of n - 2, which is exactly what the recursive case here is "saying".
Here's a basic iterative version:
def f_iter(n):
assert n >= 0
a, b = [[]], [[1]]
for _ in range(n):
a, b = b, [[1] + c for c in b] + [[2] + c for c in a]
return a
For the iterative version, we start from the base cases: a is set to all the compositions of 0 (there is exactly one: the empty composition), and b is set to all the compositions of 1. On each iteration, a and b are "moved forward" by one step. So after one iteration, a := F(1) and b := F(2), then a := F(2) and b := F(3), and so on.
Suppose a := F(k) and b := F(k + 1). The next value of a should be F(k + 1), which is simply the current value of b. To find the next value of b, note that:
if you add a 1 to a composition of k + 1, then you get a composition of k + 2.
if you add a 2 to a composition of k, then you get a composition of k + 2 as well.
in fact, these are the only ways to form a composition of k + 2, since we can only use 1's and 2's.
Thus, the new value of b, which is F(k + 2), is 1 plus all of the old value of b (F(k + 1)) and 2 plus all of the old value of a (F(k)).
Repeat this n times, and you end up with a := F(n) and b := F(n + 1).
Note, however, that because the length of the result is equal to Fibonacci(n+1), both functions above because unusable very quickly.

No needs some complex code to do that.
My function :
def findsum(x) :
base = [1]*x
i = 0
baseMax = ''
while i < x :
try :
baseMax += str(base[i] + base[i+1])
except IndexError :
baseMax += str(base[i])
i += 2
baseList = []
for i, n in enumerate(baseMax) :
if n == '2' :
baseList.append(baseMax[:i].replace('2', '11') + '1'*2 + baseMax[i+1:])
baseList.append(baseMax)
from itertools import permutations
results = set()
for n in baseList :
if n.count('1') and n.count('2') :
for p in sorted(permutations(n, len(n))) :
results.add(''.join(list(p)))
else :
results.add(n)
return sorted(results, key=int)
print(findsum(7))
# ['1222', '2122', '2212', '2221', '11122',
# '11212', '11221', '12112', '12121', '12211',
# '21112', '21121', '21211', '22111', '111112',
# '111121', '111211', '112111', '121111', '211111',
# '1111111']

import math
import itertools
def findCombos(n):
max2s = math.floor(n/2)
min1s = n - max2s
sets = []
#each set includes [numOfTwos,numOfOnes]
for x in range(max2s+1):
sets.append([x,n-(x*2)])
#creates sets of numberOfOnes and numberOfTwos
numsets = []
allsets = []
for x in sets:
numsets.append(x[0] * [2] + x[1] * [1])
#changes set to number form , [2,3] >> [2,2,1,1,1]
for eachset in numsets:
if 1 in eachset and 2 in eachset:
#if can be permutated(has 2 different numbers)
y = set(itertools.permutations(eachset))
#y is all the permutations for that set of numbers
for z in y:
#for each tuple in the list of tuples, append it
allsets.append(z)
else:
#otherwise just append the list as a tuple
allsets.append(tuple(eachset))
return allsets
Usage:
print(findCombos(7))
Output:
[[(1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 2), (1, 2, 1, 1, 1, 1), (1, 1, 1, 2, 1, 1), (1, 1, 2, 1, 1, 1), (2, 1, 1, 1, 1, 1), (1, 1, 1, 1, 2, 1), (1, 2, 1, 1, 2), (2, 1, 1, 1, 2), (2, 1, 2, 1, 1), (2, 1, 1, 2, 1), (1, 1, 2, 1, 2), (1, 1, 1, 2, 2), (1, 2, 2, 1, 1), (1, 2, 1, 2, 1), (1, 1, 2, 2, 1), (2, 2, 1, 1, 1), (2, 2, 1, 2), (2, 1, 2, 2), (2, 2, 2, 1), (1, 2, 2, 2)]

Related

How do you append a value to a list by a certain frequency?

I'm writing a program to analyse a frequency table with different functions (mean, median, mode, range, etc) and I have the user inputting their data in two lists and then converting those answers into lists of integers
values_input = input('First, enter or paste the VALUES, separated by spaces (not commas): ')
freq_input = input('Now enter the corresponding FREQUENCIES, separated by spaces: ')
values = values_input.split()
freq = freq_input.split()
data_list = []
For every value, I want the program to append it to data_input by the corresponding frequency.
For example (desired result):
If values was: 1 2 3 4
and frequency was: 2 5 7 1
I want data_list to be:
[1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4]
At the moment I have this:
for i in range(len(values)):
j = 3
while j != 0:
data_input.append(values[i])
j -= 1
But that only appends the values to data_input 3 times instead of the frequency
a = input("First, enter or paste the VALUES, separated by spaces (not commas): ").split()
b = input("Now enter the corresponding FREQUENCIES, separated by spaces: ").split()
a = [int(i) for i in a]
b = [int(i) for i in b]
x = []
y = 0
for elem in a:
temp = []
temp.append(elem)
x.append(temp * b[0+y])
y += 1
final = []
for lst in x:
for elem in lst:
final.append(elem)
print(final)
I am also a newbie. I know there are more efficient ways, but for now I have come up with this.
You can use list multiplication to create a list of each value with the appropriate frequency. zip the two lists together to get the matching values for each index:
values = [1,2,3,4]
freq = [2,5,7,1]
result = []
for v, f in zip(values, freq):
result += [v] * f
Output:
[1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4]

Generate all combinations of a list of n^2 elements with each element being from 1 to n?

I am trying to enumerate the number of valid sudokus of a given size. I have a function that takes a sudoku transformed into a list as input and checks to see if it is a valid sudoku or not. My original method was just to write nested for loops to check every single combination of a list. For a 2 x 2 sudoku, my code looks something like this:
def enumerate2x2():
cnt = 0
for i1 in range(1,3):
for i2 in range(1,3):
for i3 in range(1,3):
for i4 in range(1,3):
if checkValidSudoku([i1, i2, i3, i4]):
cnt += 1
print(cnt)
This code just generates every possible combination of a 4-element list (that's how many squares are in a 2x2 sudoku) with each element in the list being either a 1 or a 2. It then checks each combination.
However, when trying this on a 5x5 sudoku i ran into a problem as python only allows you to have 20 nested loops, so I want to generalize this ugly method into something that will work with any size sudoku. Any help would be appreciated.
The Python product intrinsic function, just importing the itertools module, is what you need:
import itertools
sudoku = list(itertools.product(range(1,3), repeat=4))
for x in range(len(sudoku)):
print sudoku[x]
that simply calculate all the cartesian products, you were looking for, here below the output:
(1, 1, 1, 1)
(1, 1, 1, 2)
(1, 1, 2, 1)
(1, 1, 2, 2)
(1, 2, 1, 1)
(1, 2, 1, 2)
(1, 2, 2, 1)
(1, 2, 2, 2)
(2, 1, 1, 1)
(2, 1, 1, 2)
(2, 1, 2, 1)
(2, 1, 2, 2)
(2, 2, 1, 1)
(2, 2, 1, 2)
(2, 2, 2, 1)
(2, 2, 2, 2)
it seems no combination is now missing, isn't it? Have a look at this other question Combinations with repetition in python, where order MATTERS for more details on alternative implementation too.

How to find indices and combinations that adds upto given sum?

How to find the combinations and corresponding indices that adds upto given sum ?
And also, can it be handled list of elements of size 500000 (higher size) ?
Input:
l1 = [9,1, 2, 7, 6, 1, 5]
target = 8
**Constraints**
1<=(len(l1))<=500000
1<=each_list_element<=1000
Output:
Format : {index:element}
{1:1, 5:1, 4:6} #Indices : 1,5,4 Elements : 1,1,6
{1:1, 2:2, 6:5}
{5:1, 2:2, 6:5}
{1:1, 3:7}
{5:1, 3:7}
{2:2, 4:6}
Tried:
from itertools import combinations
def test(l1, target):
l2 = []
l3 = []
if len(l1) > 0:
for r in range(0,len(l1)+1):
l2 += list(combinations(l1, r))
for i in l2:
if sum(i) == target:
l3.append(i)
return l3
l1 = [9,1, 2, 7, 6, 1, 5]
target = 8
print(test(l1,target))
[(1, 7), (2, 6), (7, 1), (1, 2, 5), (1, 6, 1), (2, 1, 5)]
Can someone guide me ?
UPDATE
Apart from above, code fails to handle these scenarios
Input = [4,6,8,5,3]
target = 3
Outputs {} , need to output {4:3}
Input = [4,6,8,3,5,3]
target = 3
Outputs {} , need to output {5:3,3:3} #corrected index
Input = [1,2,3,15]
target = 15
Outputs = {}, need to output {3:15}
Your code was close, i would use enumerate to get the index and value as tuple pairs. I am always dropping any of the index and value tuples where that value is greater than the target since that cannot possible be a match. this will generate less combinations. Then like you i just iterate through the permutations of tuples and sum the values in each permutation, if it sums to the target then yield that permutation. lastly in the loop to output the values i give the perm to dict to convert into the dict format you wanted
from itertools import combinations
def find_sum_with_index(l1, target):
index_vals = [iv for iv in enumerate(l1) if iv[1] < target]
for r in range(1, len(index_vals) + 1):
for perm in combinations(index_vals, r):
if sum([p[1] for p in perm]) == target:
yield perm
l1 = [9, 1, 2, 7, 6, 1, 5]
target = 8
for match in find_sum_with_index(l1, target):
print(dict(match))
OUTPUT
{1: 1, 3: 7}
{2: 2, 4: 6}
{3: 7, 5: 1}
{1: 1, 2: 2, 6: 5}
{1: 1, 4: 6, 5: 1}
{2: 2, 5: 1, 6: 5}
You can just use index function to get index and store them as key:value pair with help of dictionary in another list such as following,
from itertools import combinations
def test(l1, target):
l2 = []
l3 = []
l4=[]
dict1={}
a=0
if len(l1) > 0:
for r in range(0,len(l1)+1):
l2 += list(combinations(l1, r))
for i in l2:
dict1={}
if sum(i) == target:
for j in i:
a=l1.index(j)
dict1[a]=j
l4.append(dict1)
l3.append(i)
return l4
l1 = [4,6,8,5,3]
target = 3
print(test(l1,target))
output:
[{4: 3}]
as you can see the condition l1 = [4,6,8,5,3] target = 3 works which is previously not working.
Hope this helps!

How do I create a rollover counter within a list in Python?

I need to build a rollover counter within a list in python. Given a starting list of a variable length startlist, and all terms minnum, the counter should increment index 0 by one until it reaches maxnum, at which point index 0 resets to minnum and index one increments by one. This continues until all terms of the list are maxnum, at which point the loop should end. Here is an example.
minnum = 1, maxnum = 2, startlist = [1, 1, 1] The counting begins. [1, 1, 1] -> [2, 1, 1] -> [1, 2, 1] -> [2, 2, 1] -> [1, 1, 2] -> [2, 1, 2] -> [1, 2, 2] -> [2, 2, 2] -> end
I have tried a lot of code but nothing seems to work. If someone could please help me out with this that would be much appreciated.
Maybe you can use itertools:
from itertools import product
def main():
minimum = 1
maximum = 2
num_counters = 3
# Build the counter values iterable object
counter_range = range(minimum, maximum+1)
# Build the cartesian product of your counters.
# You have to reverse the generated tuples to make it match your requirements
counters = [tuple(reversed(x)) for x in product(counter_range, repeat=num_counters)]
print(counters)
if __name__ == '__main__':
main()
[(1, 1, 1), (2, 1, 1), (1, 2, 1), (2, 2, 1), (1, 1, 2), (2, 1, 2), (1, 2, 2), (2, 2, 2)]

Python - assigning digits of a number to variables [duplicate]

This question already has answers here:
How to split an integer into a list of digits?
(10 answers)
Closed last month.
I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.
Just create a string out of it.
myinteger = 212345
number_string = str(myinteger)
That's enough. Now you can iterate over it:
for ch in number_string:
print ch # will print each digit in order
Or you can slice it:
print number_string[:2] # first two digits
print number_string[-3:] # last three digits
print number_string[3] # forth digit
Or better, don't convert the user's input to an integer (the user types a string)
isbn = raw_input()
for pos, ch in enumerate(reversed(isbn)):
print "%d * %d is %d" % pos + 2, int(ch), int(ch) * (pos + 2)
For more information read a tutorial.
while number:
digit = number % 10
# do whatever with digit
# remove last digit from number (as integer)
number //= 10
On each iteration of the loop, it removes the last digit from number, assigning it to digit.
It's in reverse, starts from the last digit, finishes with the first
list_of_ints = [int(i) for i in str(ISBN)]
Will give you a ordered list of ints. Of course, given duck typing, you might as well work with str(ISBN).
Edit: As mentioned in the comments, this list isn't sorted in the sense of being ascending or descending, but it does have a defined order (sets, dictionaries, etc in python in theory don't, although in practice the order tends to be fairly reliable). If you want to sort it:
list_of_ints.sort()
is your friend. Note that sort() sorts in place (as in, actually changes the order of the existing list) and doesn't return a new list.
On Older versions of Python...
map(int,str(123))
On New Version 3k
list(map(int,str(123)))
(number/10**x)%10
You can use this in a loop, where number is the full number, x is each iteration of the loop (0,1,2,3,...,n) with n being the stop point. x = 0 gives the ones place, x = 1 gives the tens, x = 2 gives the hundreds, and so on. Keep in mind that this will give the value of the digits from right to left, so this might not be the for an ISBN but it will still isolate each digit.
Convert it to string and map over it with the int() function.
map(int, str(1231231231))
Recursion version:
def int_digits(n):
return [n] if n<10 else int_digits(n/10)+[n%10]
Converting to str is definitely slower then dividing by 10.
map is sligthly slower than list comprehension:
convert to string with map 2.13599181175
convert to string with list comprehension 1.92812991142
modulo, division, recursive 0.948769807816
modulo, division 0.699964046478
These times were returned by the following code on my laptop:
foo = """\
def foo(limit):
return sorted(set(map(sum, map(lambda x: map(int, list(str(x))), map(lambda x: x * 9, range(limit))))))
foo(%i)
"""
bar = """\
def bar(limit):
return sorted(set([sum([int(i) for i in str(n)]) for n in [k *9 for k in range(limit)]]))
bar(%i)
"""
rac = """\
def digits(n):
return [n] if n<10 else digits(n / 10)+[n %% 10]
def rabbit(limit):
return sorted(set([sum(digits(n)) for n in [k *9 for k in range(limit)]]))
rabbit(%i)
"""
rab = """\
def sum_digits(number):
result = 0
while number:
digit = number %% 10
result += digit
number /= 10
return result
def rabbit(limit):
return sorted(set([sum_digits(n) for n in [k *9 for k in range(limit)]]))
rabbit(%i)
"""
import timeit
print "convert to string with map", timeit.timeit(foo % 100, number=10000)
print "convert to string with list comprehension", timeit.timeit(bar % 100, number=10000)
print "modulo, division, recursive", timeit.timeit(rac % 100, number=10000)
print "modulo, division", timeit.timeit(rab % 100, number=10000)
After own diligent searches I found several solutions, where each has advantages and disadvantages. Use the most suitable for your task.
All examples tested with the CPython 3.5 on the operation system GNU/Linux Debian 8.
Using a recursion
Code
def get_digits_from_left_to_right(number, lst=None):
"""Return digits of an integer excluding the sign."""
if lst is None:
lst = list()
number = abs(number)
if number < 10:
lst.append(number)
return tuple(lst)
get_digits_from_left_to_right(number // 10, lst)
lst.append(number % 10)
return tuple(lst)
Demo
In [121]: get_digits_from_left_to_right(-64517643246567536423)
Out[121]: (6, 4, 5, 1, 7, 6, 4, 3, 2, 4, 6, 5, 6, 7, 5, 3, 6, 4, 2, 3)
In [122]: get_digits_from_left_to_right(0)
Out[122]: (0,)
In [123]: get_digits_from_left_to_right(123012312312321312312312)
Out[123]: (1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 1, 3, 1, 2, 3, 1, 2, 3, 1, 2)
Using the function divmod
Code
def get_digits_from_right_to_left(number):
"""Return digits of an integer excluding the sign."""
number = abs(number)
if number < 10:
return (number, )
lst = list()
while number:
number, digit = divmod(number, 10)
lst.insert(0, digit)
return tuple(lst)
Demo
In [125]: get_digits_from_right_to_left(-3245214012321021213)
Out[125]: (3, 2, 4, 5, 2, 1, 4, 0, 1, 2, 3, 2, 1, 0, 2, 1, 2, 1, 3)
In [126]: get_digits_from_right_to_left(0)
Out[126]: (0,)
In [127]: get_digits_from_right_to_left(9999999999999999)
Out[127]: (9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)
Using a construction tuple(map(int, str(abs(number)))
In [109]: tuple(map(int, str(abs(-123123123))))
Out[109]: (1, 2, 3, 1, 2, 3, 1, 2, 3)
In [110]: tuple(map(int, str(abs(1412421321312))))
Out[110]: (1, 4, 1, 2, 4, 2, 1, 3, 2, 1, 3, 1, 2)
In [111]: tuple(map(int, str(abs(0))))
Out[111]: (0,)
Using the function re.findall
In [112]: tuple(map(int, re.findall(r'\d', str(1321321312))))
Out[112]: (1, 3, 2, 1, 3, 2, 1, 3, 1, 2)
In [113]: tuple(map(int, re.findall(r'\d', str(-1321321312))))
Out[113]: (1, 3, 2, 1, 3, 2, 1, 3, 1, 2)
In [114]: tuple(map(int, re.findall(r'\d', str(0))))
Out[114]: (0,)
Using the module decimal
In [117]: decimal.Decimal(0).as_tuple().digits
Out[117]: (0,)
In [118]: decimal.Decimal(3441120391321).as_tuple().digits
Out[118]: (3, 4, 4, 1, 1, 2, 0, 3, 9, 1, 3, 2, 1)
In [119]: decimal.Decimal(-3441120391321).as_tuple().digits
Out[119]: (3, 4, 4, 1, 1, 2, 0, 3, 9, 1, 3, 2, 1)
Use the body of this loop to do whatever you want to with the digits
for digit in map(int, str(my_number)):
I have made this program and here is the bit of code that actually calculates the check digit in my program
#Get the 10 digit number
number=input("Please enter ISBN number: ")
#Explained below
no11 = (((int(number[0])*11) + (int(number[1])*10) + (int(number[2])*9) + (int(number[3])*8)
+ (int(number[4])*7) + (int(number[5])*6) + (int(number[6])*5) + (int(number[7])*4) +
(int(number[8])*3) + (int(number[9])*2))/11)
#Round to 1 dp
no11 = round(no11, 1)
#explained below
no11 = str(no11).split(".")
#get the remainder and check digit
remainder = no11[1]
no11 = (11 - int(remainder))
#Calculate 11 digit ISBN
print("Correct ISBN number is " + number + str(no11))
Its a long line of code, but it splits the number up, multiplies the digits by the appropriate amount, adds them together and divides them by 11, in one line of code. The .split() function just creates a list (being split at the decimal) so you can take the 2nd item in the list and take that from 11 to find the check digit. This could also be made even more efficient by changing these two lines:
remainder = no11[1]
no11 = (11 - int(remainder))
To this:
no11 = (11 - int(no11[1]))
Hope this helps :)
Similar to this answer but more a more "pythonic" way to iterate over the digis would be:
while number:
# "pop" the rightmost digit
number, digit = divmod(number, 10)
How about a one-liner list of digits...
ldigits = lambda n, l=[]: not n and l or l.insert(0,n%10) or ldigits(n/10,l)
Answer: 165
Method: brute-force! Here is a tiny bit of Python (version 2.7) code to count'em all.
from math import sqrt, floor
is_ps = lambda x: floor(sqrt(x)) ** 2 == x
count = 0
for n in range(1002, 10000, 3):
if n % 11 and is_ps(sum(map(int, str(n)))):
count += 1
print "#%i: %s" % (count, n)
Just assuming you want to get the i-th least significant digit from an integer number x, you can try:
(abs(x)%(10**i))/(10**(i-1))
I hope it helps.

Resources