使用Python3计算列表中多个INT的功率的最佳方法是什么?



所以我所拥有的是诸如[2、2、2、3,...,n]之类的整数列表,列表的长度可以从1到100。我需要做的是计算所有数字的功能。这应该非常容易,但是也有规定,您必须将每个数字提高到下一个数字的幂等,依此类推。例如:如果列表包含[2、3、4],则首先需要计算3^4,然后是2^(回答3^4)。如果列表更长,则需要计算所有这些值的值。上面的示例[2,3,4]应返回2^81,应该是2417851639229258349412352根据Wolfram的说法。即使它只是一种算法(我可以从那里找出代码),任何帮助都会很棒,我只是在努力提出了一段时间的算法。

这是我现在有的一些代码...

temp = [] 
length = 0
for num in powernumbers:
    for index in num:
        if index.isdigit():
            temp.append(index)
        length = len(temp)
    if length > 0:
        for j in reversed(range(len(temp))):
            _temp = math.pow(int(temp[j-1]), int(temp[j]))
            #THE ABOVE CODE WILL ONLY WORK FOR A LIST OF LEN 2
        print(_temp)
        #needs math.pow(0,(math.pow(1,(math.pow(2,...)))))
print("TEMP:", temp)

再次感谢任何帮助!

您可以将functools.reduce与反向列表使用:

>>> from functools import reduce
>>> l = [2, 3, 4]
>>> reduce(lambda x, y: y**x, reversed(l))
2417851639229258349412352

reduce采用两个参数:功能和迭代。然后,它将累积地应用该函数,以将峰值减少到单个值。该函数的第一个参数是降低值,第二个参数来自Itable。由于我们想以相反顺序处理列表,因此我们使用reversed,以便首先执行3**4

请注意,在Python 2 reduce上是内置的,因此无需导入任何内容。

>>> numbers = [2,3,4] # your list
>>> result = 1
>>> for n in reversed(numbers):
        result = n**result

>>> result
2417851639229258349412352
>>> 

首先在1上初始化结果,然后以相反顺序浏览列表,将数字提高到上一个结果,这是第一次是1个示例的结果。

result = 4**1 -> 4
result = 3**4 -> 81
result = 2**81 -> 2417851639229258349412352

但是请注意,这种嵌套的指数将非常快地增长,您更有可能会因疯狂的大数字而遇到记忆错误

>>> result = 1
>>> powers = [2,2,2,2,2,2]
>>> for n in reversed(powers):
        result = n**result

Traceback (most recent call last):
  File "<pyshell#60>", line 2, in <module>
    result = n**result
MemoryError
>>> 

弹出列表中的最后一个元素,然后向后浏览列表并保持指定。

powernumbers = [2, 3, 4]
result = powernumbers.pop()
for num in powernumbers[::-1]:
    result = num**result

结果:

>>> result
2417851639229258349412352

最新更新