Last active
August 29, 2015 14:10
-
-
Save mahendrakalkura/40e671bc9408bc4ef71c to your computer and use it in GitHub Desktop.
An algorithm whose name I cannot remember!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
def is_valid(s, q, p): | |
for k in xrange(0, q - p): | |
if s[k] != s[k + p]: | |
return False | |
return True | |
def solution(N): | |
s = bin(N)[2:] | |
q = len(s) | |
# (q / 2) + 1 => to handle both odd and even numbered cases of "s" | |
for p in xrange(1, (q / 2) + 1): | |
# This is not memory optimized | |
''' | |
if not [k for k in xrange(0, q - p) if s[k] != s[k + p]]: | |
return p | |
''' | |
# This is not stack optimized but still preferable over the previous one | |
if is_valid(s, q, p): | |
return p | |
return -1 | |
assert solution(955) == 4 | |
assert solution(102) == -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment