我了解错误背后的信息,但是在了解如何克服错误时迷路了。我正在尝试做的是,在for / loop中,名为pancake
的变量将来自先前迭代pancake[i - 1]
的值用作函数exit
调用的第一个参数的输入。
我遇到的错误:
TypeError: 'float' object does not support item assignment
我的代码:
def exit(number):
def son():
geometric = (math.exp(2))
pancake = number * geometric
return pancake
return son()
pancake_ac = exit()()
pancake_ac[0] = pancake_ac
for i in range(1, 10):
pancake_ac[i] = exit(pancake_ac[i - 1])
答案 0 :(得分:1)
precio_accion
不是list
或dict
,而是浮点数,因此根本不需要precio_accion[0] = precio_accion
行。如果您想要list
:
import math
import random
def funcion_gbm(pi = 100, media = 0.10, volatilidad = 0.05):
m = media
v = volatilidad
def funcion_anidada():
exponencial = math.exp((m - (1/2) * v**2) * (1/365) +
v * math.sqrt(1/365) * random.normalvariate(0, 1))
precio = pi * exponencial
return precio
return funcion_anidada
precio_accion = funcion_gbm()()
# Now precio_accion is a list and your iteration will work
precio_accion = [precio_accion]
现在让我们进入循环。首先,您的target_price
不变,那么为什么要重新定义它呢?您可以在循环外定义一次:
target_price = 125
for rueda in range(1,1000):
# Now you need to append to the list rather than trying to
# access other elements that aren't in the list yet
precio_accion.append(funcion_gbm(precio_accion[rueda - 1]))
# You're comparing the last item in the list every time, so
# you can just access it with -1
if precio_accion[-1] == target_price:
print("reached")
# No need for else since it's just continuing the loop