python - 我正在尝试找到第 n 个二进制回文

标签 python algorithm binary palindrome

Binary palindromes: numbers whose binary expansion is palindromic.
Binary Palindrome -> 是一个二进制表示为回文的数字。
Here is link to the solution with naive approach

我已经阅读了上面的链接,它给出了一个公式来找到第 n 个二进制回文。我无法理解,因此无法编写解决方案。

def palgenbase2(): # generator of palindromes in base 2
    #yield 0
    x, n, n2 = 1, 1, 2
    m = 1;
    while True:
        for y in range(n, n2):
            s = format(y, 'b')
            yield int(s+s[-2::-1], 2)
        for y in range(n, n2):
            s = format(y, 'b')
            yield int(s+s[::-1], 2)
        x += 1
        n *= 2
        n2 *= 2
        if n2 > 1000000000:
            break

ans = {}

for i,j in  enumerate(palgenbase2()):
    print i,j
    ans[i]=j

with open("output","a") as f:
    f.write(ans)

#use the saved output to give answer to query later
#this will work but it takes too much time.

n = int(raw_input())
for c in range(0,n):
    z = int(raw_input())
    print ans[z]

这是一段 Python 代码,但它会生成所有此类回文。
我在程序中需要帮助才能直接得到第n个二进制回文。
如下:

Input -> 1 <= n <= 1000000000
Function -> f(n)
output -> nth binary palindrome.

我们能否使用提到的公式在更短的时间内做到这一点 here

最佳答案

这是在 A006995 中给出的递归算法的一个相当直接的实现。 .

为了提高效率,我使用位移位来执行二进制求幂:当 x 时是一个非负整数,1 << x相当于2 ** x但速度要快得多(至少,它在标准 CPython 上的 Python 2 和 Python 3 中都是如此)。

此外,为了使递归更有效,该函数将先前计算的值存储在字典中。这也让我们很容易处理 n <= 2 ,递归公式本身不处理。

#!/usr/bin/env python

''' Binary palindromes

    Find (non-negative) integers which are palindromes when written in binary

    See http://stackoverflow.com/q/39675412/4014959
    and https://oeis.org/A006995

    Written by PM 2Ring 2016.09.24

    Recursion for n>2: a(n)=2^(2k-q)+1+2^p*a(m), where k:=floor(log_2(n-1)), and p, q and m are determined as follows:

    Case 1: If n=2^(k+1), then p=0, q=0, m=1;

    Case 2: If 2^k<n<2^k+2^(k-1), then set i:=n-2^k, p=k-floor(log_2(i))-1, q=2, m=2^floor(log_2(i))+i;

    Case 3: If n=2^k+2^(k-1), then p=0, q=1, m=1;

    Case 4: If 2^k+2^(k-1)<n<2^(k+1), then set j:=n-2^k-2^(k-1), p=k-floor(log_2(j))-1, q=1, m=2*2^floor(log_2(j))+j; 
'''

#Fast Python 3 version of floor(log2(n))
def flog2(n):
    return n.bit_length() - 1

def binpal(n, cache={1:0, 2:1, 3:3}):
    if n in cache:
        return cache[n]

    k = flog2(n - 1)
    b = 1 << k
    a, c = b >> 1, b << 1

    if n == c:
        p, q, m = 0, 0, 1
    elif b < n < a + b:
        i = n - b
        logi = flog2(i)
        p, q, m = k - logi - 1, 2, (1 << logi) + i
    elif n == a + b:
        p, q, m = 0, 1, 1
    else:
        #a + b < n < c
        i = n - a - b
        logi = flog2(i)
        p, q, m = k - logi - 1, 1, (2 << logi) + i

    result = (1 << (2*k - q)) + 1 + (1 << p) * binpal(m)
    cache[n] = result
    return result

def palgenbase2(): 
    ''' generator of binary palindromes '''
    yield 0
    x, n, n2 = 1, 1, 2
    while True:
        for y in range(n, n2):
            s = format(y, 'b')
            yield int(s+s[-2::-1], 2)
        for y in range(n, n2):
            s = format(y, 'b')
            yield int(s+s[::-1], 2)
        x += 1
        n *= 2
        n2 *= 2

gen = palgenbase2()

for i in range(1, 30):
    b = next(gen)
    c = binpal(i)
    print('{0:>2}: {1} {1:b} {2}'.format(i, b, c))

输出

 1: 0 0 0
 2: 1 1 1
 3: 3 11 3
 4: 5 101 5
 5: 7 111 7
 6: 9 1001 9
 7: 15 1111 15
 8: 17 10001 17
 9: 21 10101 21
10: 27 11011 27
11: 31 11111 31
12: 33 100001 33
13: 45 101101 45
14: 51 110011 51
15: 63 111111 63
16: 65 1000001 65
17: 73 1001001 73
18: 85 1010101 85
19: 93 1011101 93
20: 99 1100011 99
21: 107 1101011 107
22: 119 1110111 119
23: 127 1111111 127
24: 129 10000001 129
25: 153 10011001 153
26: 165 10100101 165
27: 189 10111101 189
28: 195 11000011 195
29: 219 11011011 219

如果您需要在 Python 2 上运行它,您将无法使用那个 flog2函数,因为 Python 2 整数没有 bit_length方法。这是一个替代版本:

from math import floor, log

def flog2(n):
    return int(floor(log(n) / log(2)))

关于python - 我正在尝试找到第 n 个二进制回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39675412/

相关文章:

java - 索引为 0 而不是索引 1 的 heapSort 的 maxheap 方法

python - 提高性能 : Remove all strings in a (big) list appearing only once

algorithm - 为什么二进制搜索索引以这种方式计算?

javascript - 为什么按位与在JavaScript中运算0b0010&0b0011001100110011001100110011001100110011001100110011001100110011时给出零

javascript - 更改 MongoDB 中的二进制子类型

python - python 推特搜索没有结果

python - 创建新日期时如何解决 "type object ' datetime.datetime' has no attribute 'timedelta' "?

c - 如何阻止文件名/路径出现在已编译的 C 二进制文件中

python - 使用切片反转列表 [ : 0:-1] in Python

python - 从非 R 脚本(例如 Python)访问/提取 R 帮助