Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

python - How to parse strings into variable/function/float/integer assignment/values?

I want to write a summation function, but can't figure out how I would parse the bottom expression and right expression.

def summation(count: float, bottom_var: str, espression: str):
    out = 0
    
    for char in bottom_var:
        pass # somehow parse
    for char in expression:
        pass # somehow parse

I want you to be able to use the inputs the same way as in normal sigma notation, as in bottom_var is 'n=13', not '13'.

EDIT: To clarify, I mean I want someone to be able to input an assignment under bottom_var, , and then it being usable within expression, but nowhere else.

Example:

summation(4, 'x=1', 'x+1')

(would return 14, as 2+3+4+5=14)

question from:https://stackoverflow.com/questions/65650721/how-to-parse-strings-into-variable-function-float-integer-assignment-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, parse the bottom_var to get the symbol and starting value:

var, value = bottom_var.split('=')
var = var.strip()
value = eval(value)

Using split we get the two parts of the equal sign easily. Using strip we even allow any number of spaces, like x = 1.

Then, we want to create a loop from the starting value to count:

for i in range(value, count+1):
    ...

Lastly, we want to use the loop to sum the expression when each time the symbol is replaced with the current iteration's value. All in all:

def summation(count: int, bottom_var: str, expression: str):
    var, value = bottom_var.split('=')
    var = var.strip()
    value = eval(value)
    res = 0
    for i in range(value, count+1):
        res += eval(expression.replace(var, str(i)))

    return res

For example:

>>> summation(4, 'x=1', 'x+1')
14

Proposing the code in this answer, I feel the need to ask you to read about Why is using 'eval' a bad practice? and please make sure that it is OK for your application. Notice that depending on the context of the use of your code, using eval can be quite dangerous and lead to bad outcomes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...