I am learning to write efficient code in Python.
I came across a problem wherein I had to check divisibility by 8 of all possible combinations of 968 or maybe even a larger int
(not sure about long int
but let's say including those as well). So how can I do that efficiently?
I think breaking it up and using ''.join()
is giving me a Segmentation Error
and Runtime Error
in few cases.
Ex: 968 combinations are:
[('9',), ('6',), ('8',), ('9', '6'), ('9', '8'), ('6', '8'), ('9', '6', '8')]`enter code here`
Edited - Question is am I doing it efficiently? or can I reduce my time with any other import? Everything (including stackoverflow) is very new to me)
import itertools
import math
n = 8 #example
string = '968' #example
lis=[]
# we will use combinations(string,i) for creating sorted ordered
#non-repeating tuples combinations('ABCD', 2) ---> AB AC AD BC BD CD
for i in range(1,n+1):
lis+=list(itertools.combinations(string,i))
print lis
#output is [('9',), ('6',), ('8',), ('9', '6'), ('9', '8'), ('6', '8'), ('9', '6', '8')]
fin=[]
#we will join all tuple-item and append it in fin ---> ''.join()
for item in lis:
fin.append(int(''.join(item)))
print fin
#output is [9,6,8,96,98,68,968]
ans=[]
#we will check divisibility with 8
for item in fin:
if item%8==0:
ans.append(item)
print ans
#ouput is [8,96,968]