我想使用python执行计算,其中等式的当前值(i)基于等式(i-1)的先前值,这在电子表格中很容易做但我会而是学会编码
我注意到有大量关于从列表中查找上一个值的信息,但我没有列表需要创建它!我的等式如下所示。
h=(2*b)-h[i-1]
任何人都可以告诉我一种方法吗?
我试过这种事情,但这不会起作用,因为我试图做方程式我正在调用一个我还没有创建的值,如果我设置h = 0然后我得到一个错误,我是超出指数范围
i = 1
for i in range(1, len(b)):
h=[]
h=(2*b)-h[i-1]
x+=1
答案 0 :(得分:0)
h = []
for i in range(len(b)):
if i>0:
h.append(2*b - h[i-1])
else:
# handle i=0 case here
答案 1 :(得分:0)
h = [b[0]]
for val in b[1:]:
h.append(2 * val - h[-1]) # As you add to h, you keep up with its tail
用于大 b 列表(brr,单字母标识符),以避免创建大切片
from itertools import islice # For big list it will keep code less wasteful
for val in islice(b, 1, None):
....
答案 2 :(得分:0)
正如@pad所指出的,你只需要处理接收第一个样本的基本情况。
然而,除了检索先前的结果之外,你的等式不使用 i 。它看起来更像是一个运行过滤器而不是需要维护过去值列表的东西(一个可能永远不会停止增长的数组)。
如果是这种情况,并且您只想要最近的值,那么您可能想要使用生成器。
def gen():
def eqn(b):
eqn.h = 2*b - eqn.h
return eqn.h
eqn.h = 0
return eqn
然后使用
>>> f = gen()
>>> f(2)
4
>>> f(3)
2
>>> f(2)
0
>>>
使用yield和send可以使用真正的生成器实现相同的效果。
答案 3 :(得分:0)
首先,您需要所有中间值吗?也就是说,您是否需要从h
到0
的列表i
?或者你只是想要h[i]
?
如果您只需要第i个值,那么我们可以递归:
def get_h(i):
if i>0:
return (2*b) - get_h(i-1)
else:
return h_0
但请注意,这对大型i不起作用,因为它将超过最大递归深度。 (感谢你指出这个kdopen)在这种情况下,一个简单的for循环或生成器更好。
更好的是使用(数学上)闭合形式的等式(对于你可能的例子,它可能不在其他情况下):
def get_h(i):
if i%2 == 0:
return h_0
else:
return (2*b)-h_0
在这两种情况下,h_0
都是您开始使用的初始值。
答案 4 :(得分:0)
您正在将函数(等式)连续应用于该函数的先前应用的结果 - 该过程需要种子启动它。您的结果如下[seed, f(seed), f(f(seed)), f(f(f(seed)), ...]
。这个概念是function composition
。您可以创建一个通用函数来为任何函数序列执行此操作,Python函数是第一类对象,可以像任何其他对象一样传递。如果需要保留中间结果,请使用生成器。
def composition(functions, x):
""" yields f(x), f(f(x)), f(f(f(x)) ....
for each f in functions
functions is an iterable of callables taking one argument
"""
for f in functions:
x = f(x)
yield x
您的规格需要种子和常数,
seed = 0
b = 10
等式/函数,
def f(x, b = b):
return 2*b - x
f
已应用b
次。
functions = [f]*b
用法
print list(composition(functions, seed))
如果不需要中间结果,composition
可以重新定义为
def composition(functions, x):
""" Returns f(x), g(f(x)), h(g(f(x)) ....
for each function in functions
functions is an iterable of callables taking one argument
"""
for f in functions:
x = f(x)
return x
print composition(functions, seed)
或者更一般地说,对呼叫签名没有限制:
def compose(funcs):
'''Return a callable composed of successive application of functions
funcs is an iterable producing callables
for [f, g, h] returns f(g(h(*args, **kwargs)))
'''
def outer(f, g):
def inner(*args, **kwargs):
return f(g(*args, **kwargs))
return inner
return reduce(outer, funcs)
def plus2(x):
return x + 2
def times2(x):
return x * 2
def mod16(x):
return x % 16
funcs = (mod16, plus2, times2)
eq = compose(funcs) # mod16(plus2(times2(x)))
print eq(15)
虽然流程定义似乎是递归的,但我抵制了诱惑,所以我可以远离maximum recursion depth
hades。
我很好奇,搜索了function composition
的SO,当然,还有很多相关的Q& A&#39}。