The thing is that range
and xrange
are written in C, hence they are prone to overflows. You need to write your own number generator to surpass the limit of C long
.
def my_range(end):
start = 0
while start < end:
yield start
start +=1
def conforms(k,s):
k = k + 1
if s.find("0" * k) == -1 and s.find("1" * k) == -1:
return True
else:
return False
def brute(n,k,s):
min_val = n + 1
min_str = ""
desired = long(s,2)
for i in my_range(2 ** n):
xor = desired ^ i # gives number of bit changes
i_rep = bin(i)[2:].zfill(n) # pad the binary representation with 0s - for conforms()
one_count = bin(xor).count('1')
if one_count < min_val and conforms(k, i_rep):
min_val = bin(xor).count('1')
min_str = i_rep
return (min_val,min_str)
T = 1
for i in range(T):
words = [100, 1]
start="00000001"
sol = brute(words[0], words[1], start)
print sol[0]
print sol[1]
12
solved Python Code Fails