【问题标题】:Power of elements in list列表中元素的幂
【发布时间】:2019-05-05 20:41:22
【问题描述】:

我有这个示例代码:

n = 11698030645065745910098695770921
e = 9569991810443215702618212520777
d = 7874909554574080825236064017913
m = 104228568138
m = int(m)
e = int(e)
n = int(n)
def preparation(m, n):
    block_lenght= len(str(n)) - 1
    m = [str(m)[i:i+block_lenght] for i in range(0, len(str(m)), block_lenght)]
    return m

def encrypt(m, n, e):
    m = preparation(m, n)

    power = [int(i) ** e for i in m]

    modulo = [i%n for i in power]

    total_sum = sum(modulo)

    return total_sum

m = encrypt(m, n, e)
print("m = ", m)

你能告诉我为什么这个算法对于这么大的数字这么慢吗?我怎样才能让它更快?

【问题讨论】:

    标签: python-3.x modulo pow


    【解决方案1】:

    另一种方法是使用 lambda 应用映射。

    http://book.pythontips.com/en/latest/map_filter.html

    a_to_power_e = list(map(lambda x : int(x)**e, a))
    
    a_modulo_n = list(map(lambda x : int(x)%n, a_to_power_e))
    

    如果你想多次重复使用同一个函数,你可以在下面做。

    cust_power_func = lambda x : int(x)**e
    cust_modulo_func = lambda x : int(x)%n
    a_to_power_e = list(map(cust_power_func, a))
    
    a_modulo_n = list(map(cust_modulo_func, a_to_power_e))
    

    【讨论】:

      【解决方案2】:

      您可以先使用内置的pow 函数或使用** 运算符来创建列表power。两种实现见下文:

      In [1777]: n = 43787
            ...: e = 31
      In [1778]: a
      Out[1778]: ['1112', '2222', '3323', '4']
      
      In [1781]: power = [pow(int(i),e) for i in a]
      

      In [1786]: power = [int(i) ** e for i in a]
      

      然后,在上面创建的电源列表的每个元素上创建另一个列表modulo

      In [1784]: modulo = [i%n for i in power]
      
      In [1785]: modulo
      Out[1785]: [19378L, 27732L, 26928L, 30208]
      

      创建了另一个函数来计算power。尝试检查性能是否因此而提高:

      MOD = 1000000007
      def fast_power(base, power):
          result = 1
          while power > 0:
              # If power is odd
              if power % 2 == 1:
                  result = (result * base) % MOD
      
              # Divide the power by 2
              power = power / 2
              # Multiply base to itself
              base = (base * base) % MOD
      

      【讨论】:

      • 所以我实现了你的代码来挖掘它,它适用于小数字,但现在当我得到这么大的数字时,算法是如此缓慢。有什么建议吗?我的旧问题现在被新问题取代了。
      • 引入了另一个函数来计算power。请检查我的更新答案。
      • 我有错误“名称'MOD'未定义”所以我需要设置一些东西为MOD
      • 对不起,MOD = 1000000007
      • def fast_power(base, power): MOD = 1000000007 result = 1 while power > 0: # If power is odd if power % 2 == 1: result = (result * base) % MOD # Divide the power by 2 power = power / 2 # Multiply base to itself base = (base * base) % MOD return result k = fast_power(m, e)
      猜你喜欢
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多