将给定字母表的字符串转换为整数

时间:2017-03-26 10:41:39

标签: python algorithm

我有一个工作函数,它将整数转换为给定字母A的长度为k的字符串

def ToString(x, k, A):
    """
    Args:
       x (int):     Integer x ∈ N
       k (int)      String length k >= log_N (x)
       A (list)     Alphabet A = {c_1, ..., c_N}
    """

    S = ""
    N = len(A)

    for i in reversed(range(0, k)):
        s_k = A[x % N]
        x = x // N
        S += s_k

    return S

测试:

  A = ['0', '1']  # Alphabet
  k = 8           # length
  x = 5           # the number to convert
  s = ToString(x, k, A) # s = '10100000'

所以现在我基本上需要这个功能的确切反转,所以我可以转换字符串' 10100000'和给定的字母表回到5

def ToInteger(S, A):
    """    
    Args:
       S (str):     String
       A (list):    Alphabet

    Returns:
       int:         Integer
    """
    x = 0
    for i in range(len(S)):
        x = len(A) * x + len(A)-1-A.index(S[i])
    return x

不幸的是,这会返回垃圾:

i = StringToInteger('10100000',['0','1']) # = 95

这就是算法规范的样子: enter image description here

错误在哪里?

1 个答案:

答案 0 :(得分:1)

尝试使用第一个功能,S = s_k + S代替S += s_k 然后使用此功能:

def toInteger(S, A):
   x = 0
   for i in range(len(S)):
     x += (len(A) ** (len(S) - 1 - i)) * (A.index(S[i]))
   return x