繁体   English   中英

如何更快地组合电源功能?

[英]How can I make a combined power function faster?

我很快就完成了这个功能,找到列表中所有内容的组合功能,但我很确定有一种方法可以让它更快。 它返回一个2项列表,其中组合的权力和列表格式化为导出。

#The input for this function is a list of numbers (but string data type)
def find(x):
  total = int(x[0])
  for i in range (1,len(x)):
      total = total ** int(x[i])
  value = [total,'^'.join(x)]
  return value

这将比您现有的更快地计算值:

import functools
import operator

l = [2, 3, 4]

functools.reduce(operator.pow, l)
## 4096 

如果你想在列表中显示值链,就像在原始帖子中一样,你可以定义一个函数,例如:

def func(vals):
  vals_string = '^'.join(str(val) for val in vals)
  total = functools.reduce(operator.pow, vals)
  return [total, vals_string]

用法示例:

l = [2, 3, 4, 5]
result = func(l)
print(result)
## [1152921504606846976, '2^3^4^5']

您希望避免执行一堆取幂,因为这些指数很昂贵。 乘法更便宜,因此您可以通过将所有值乘以第一个值的右侧来节省计算能力,然后将第一个值提升到该幂。

from functools import reduce
from operator import mul
from typing import List

def find(x: List[int]) -> int:
  return x[0]**reduce(mul, x[1:], 1)

你也可以这样做

def find(i: int, *updog: int) -> int:
  return i ** reduce(mul, updog, 1)

并将其称为find(*[2,1,2,3,4])find(2, 1, 2, 3) find(*[2,1,2,3,4]) find(2, 1, 2, 3)

无论哪种方式,这都使用函数签名来提供更严格的保证,即设置初始值,而不是在列表为空时具有未定义的行为。

您可以使用NumPy的power.accumulate()来累积指数。 但是 ,对于大型输入列表,您很快就会遇到大量数据。 这里的[-1]为您提供所有元素的累积

import numpy as np

def find(x):
    total = np.power.accumulate(x)[-1]
    value = [total,'^'.join(map(str, inp))]
    return value

x = np.array([2,3,4,5])

print (find(x))
# [1152921504606846976, '2^3^4^5']

你可以使用functools.reduce()

from functools import reduce
import operator

reduce(operator.pow, list)

reduce()作用是将第一个参数应用于第二个参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM