简体   繁体   中英

Is the any way to use numbers on list to perform operations?

For a newcomer to python from c++ In python for example, is there a way to get this to substitute in the element in list position f[n-1], perform mathematical operations, and add it to the next element on the list?

f = [1, 1-x]
for n in range (1,5):
    f[n+1] = simplify((x*f[n-1])/n)
    print(f[n])

Is this the effect you want? It extends the list, f, one element on each iteration. I removed the simplify call, because I expect that it doesn't really affect your Python mechanics question.

x = 0.4

f = [1, 1-x]
for n in range(1,5):
    f.append((x*f[n-1]) / n)

print(f)

The output from this is

[1, 0.6, 0.4, 0.12, 0.053333333333333344, 0.012]

Now that you've clarified a little, here's a starting point for your string processing.

def simplify(expr):
    return expr

f = ["1", "1-x"]
for n in range(1, 5):
    f.append(simplify("x*(" + f[n-1] + ")/n"))
    print(f[n])

The output from this is

1-x
x*(1)/n
x*(1-x)/n
x*(x*(1)/n)/n

This leaves you with a reduced programming problem to attack: how to reduce things such as "x*(x*" to "x**2". You're tackling a bit of a parsing problem here: you'll likely have to specify a grammar and make a reasonable attack on your coding to get to the next point where we can help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM