Python Code Fails -
the following code fails. throwing exception , producing no output.
the constraints on input 1<=n<=1000, 1<=k<=n , s.length equal n. guaranteed input specified.
also, code works, when 1<=n<=20.
def conforms(k,s): k = k + 1 if s.find("0" * k) == -1 , 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) in range (2 ** n): xor = desired ^ # gives number of bit changes i_rep = bin(i)[2:].zfill(n) # pad binary representation 0s - conforms() one_count = bin(xor).count('1') if one_count < min_val , conforms(k, i_rep): min_val = bin(xor).count('1') min_str = i_rep return (min_val,min_str) t = input() in range(t): words = raw_input().split() start = raw_input() sol = brute( int(words[0]), int(words[1]), start) print sol[0] print sol[1]
the thing range
, xrange
written in c, hence prone overflows. need write own number generator surpass 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 , 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) in my_range(2 ** n): xor = desired ^ # gives number of bit changes i_rep = bin(i)[2:].zfill(n) # pad binary representation 0s - conforms() one_count = bin(xor).count('1') if one_count < min_val , conforms(k, i_rep): min_val = bin(xor).count('1') min_str = i_rep return (min_val,min_str) t = 1 in range(t): words = [100, 1] start = '00000001' sol = brute(words[0], words[1], start) print sol[0] print sol[1]
Comments
Post a Comment