Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...