在python中解决非常大的表达式

时间:2015-02-17 05:11:14

标签: python memory project

我在Project Euler中遇到一个问题,要求找到代表 e (数学常数)的连续分数的值,最多100个项。

我提出了一个很长的表达式,我几乎是正面的,但是Python无法评估它。我一直在收到MemoryError。

从透视角度来看,它是一个包含50个分数条的分数。

这是表达式:

2+(1/(1+1/(2+1/(1+1/(1+1/(4+1/(1+1/(1+1/(6+1/(1+1/(1+1/(8+1/(1+1/(1+1/(10+1/(1+1/(1+1/(12+1/(1+1/(1+1/(14+1/(1+1/(1+1/(16+1/(1+1/(1+1/(18+1/(1+1/(1+1/(20+1/(1+1/(1+1/(22+1/(1+1/(1+1/(24+1/(1+1/(1+1/(26+1/(1+1/(1+1/(28+1/(1+1/(1+1/(30+1/(1+1/(1+1/(32+1/(1+1/(1+1/(34+1/(1+1/(1+1/(36+1/(1+1/(1+1/(38+1/(1+1/(1+1/(40+1/(1+1/(1+1/(42+1/(1+1/(1+1/(44+1/(1+1/(1+1/(46+1/(1+1/(1+1/(48+1/(1+1/(1+1/(50+1/(1+1/(1+1/(52+1/(1+1/(1+1/(54+1/(1+1/(1+1/(56+1/(1+1/(1+1/(58+1/(1+1/(1+1/(60+1/(1+1/(1+1/(62+1/(1+1/(1+1/(64+1/(1+1/(1+1/(66+1/(1+1))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))

答案应该非常接近 e (2.71828)

1 个答案:

答案 0 :(得分:0)

这是一种快速评估内部字符串的方法:

def evaluate_nested_fraction(expr):

  # Allow only "safe" characters in your `eval` [digits and +-*/()]
  expr= re.sub('[^\d\+\-\*\/\)\(]+','', expr)

  # Convert into a list of expressions starting with the innermost 1+1
  # Do this by removing ')' assuming balance, splitting by '(' and reversing order
  expr = expr.replace(')','').split('(')[::-1]

  # Now evaluate and append
  value = ''
  for i in xrange(0, len(expr)):
    value = str(float(eval(expr[i] + value)))
  return value


# Let's run this on your fraction
x = '2+(1/(1+1/(2+1/(1+1/(1+1/(4+1/(1+1/(1+1/(6+1/(1+1/(1+1/(8+1/(1+1/(1+1/(10+1/(1+1/(1+1/(12+1/(1+1/(1+1/(14+1/(1+1/(1+1/(16+1/(1+1/(1+1/(18+1/(1+1/(1+1/(20+1/(1+1/(1+1/(22+1/(1+1/(1+1/(24+1/(1+1/(1+1/(26+1/(1+1/(1+1/(28+1/(1+1/(1+1/(30+1/(1+1/(1+1/(32+1/(1+1/(1+1/(34+1/(1+1/(1+1/(36+1/(1+1/(1+1/(38+1/(1+1/(1+1/(40+1/(1+1/(1+1/(42+1/(1+1/(1+1/(44+1/(1+1/(1+1/(46+1/(1+1/(1+1/(48+1/(1+1/(1+1/(50+1/(1+1/(1+1/(52+1/(1+1/(1+1/(54+1/(1+1/(1+1/(56+1/(1+1/(1+1/(58+1/(1+1/(1+1/(60+1/(1+1/(1+1/(62+1/(1+1/(1+1/(64+1/(1+1/(1+1/(66+1/(1+1))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'

print evaluate_nested_fraction(x)

在CPython上返回 2.71828182846 。您可以运行它here

eval的任何用法都附带the usual warnings