要解决的通用 Pythonic 代码:2**2**2**2**0

Generic Pythonic Code to Solve: 2**2**2**2**0

我得到下面的 python 代码来解决上面的表达式。我相信应该有一个更通用的 Pythonic 方法。我所说的通用是指它应该解决任何数字组合(不仅仅是:2 ** 2 ** 2 ** 2 ** 0)例如:3 ** 2 ** 4 ** 1 ** 0、3 ** 3 * * 1 ** 2 ** 0 等等

def get_expo(expo, index, cur_expo):
    return int(expo[index-1]) ** cur_expo


def solve_expo(expo):
    expo = expo.split("^")
    index = len(expo) - 1
    cur_expo = int(expo[-1])
    result = 0
    for i in range(len(expo)):
        if index == 1:
            result = get_expo(expo, index, cur_expo)
            return "Answer is: " + str(result)
        else:
            cur_expo = get_expo(expo, index, cur_expo)
            index -= 1



print solve_expo("2^2^2^2^0")

我需要更好的 pythonic 方法来解决它?

Python 的内置 ** 运算符已经正确地尊重优先级。您可以将完整的表达式输入它并获得您期望的答案。

>>> 3 ** 2 ** 4 ** 1 ** 0
43046721

所以编写函数的直接(但有潜在危险)的方法是这样的,只需在将 ^ 替换为 ** 后计算表达式:

def solve_expo(expression):
    return eval(expression.replace('^', '**'))

Obviously, eval might not be suitable for your situation(或者您可能只想做一些更有趣的事情),因此您可以将解决方案重写为递归解决方案。无论如何,它更优雅一些。

def solve_expo(expression):
    base, exp = expression.split('^', 1)  # Split off just the first ^
    if '^' in exp:
        return int(base) ** solve_expo(exp)  # More exponents later, so resolve them and raise our base to that power
    return int(base) ** int(exp)  # base and exp are plain numbers, so just return base^exp

由于您想将其作为递归来处理,因此这段代码似乎可以很好地处理它。拆分创建一个字符串值列表,然后在递归函数中完全处理。

val = '2^3^4^5^6^7'
vals = val.split('^')

def solve_expo(expo):
    if len(expo) == 1:
        return int(expo)
    else:
        return solve_expo(expo[:-1]) ** int(expo[-1])

solv_expo(vals)

通过使用 reduce() 函数实现此目的的替代方法:

>>> operation_str = '3^2^4^1^0'
>>> reduce(lambda x, y: int(y)**int(x), operation_str.split('^')[::-1])
43046721

基于分步操作的解释:

>>> operation_str.split('^')
['3', '2', '4', '1', '0'] # Converted str into list
>>> operation_str.split('^')[::-1]
['0', '1', '4', '2', '3'] # Reversed list
>>> reduce(lambda x, y: int(y)**int(x), operation_str.split('^')[::-1])
43046721  # Check reduce() fucntion linked above to know how it works

另请阅读:Why should exec() and eval() be avoided?