Python - lists with mathematical operations inside -
how create function takes list alternating math symbols (plus, minus) , integers return result. example, 4, '+', 5, '-', 1 should return 8.
i'll give 1 liner. if homework, teacher's going raise eyebrow's @ this. given
words = [4, '+', 5, '-', 1]
then
result = sum(digit * (-1 if sign == '-' else 1) digit, sign in zip(words[0::2], ['+'] + words[1::2]))
what we're leveraging here said '+' , '-' operands. type of number sentence can rewritten (+4) + (+5) + (-1)
. in other words, view +/- sign indicator, , sum them all.
so decomposing above...
# extract slice digits digits = words[0::2] # --> [4, 5, 1] # extract slice signs signs = words[1::2] # --> ['+', '-'] # our signs needs have same size digits, there's implicit '+' preceding first digit signs = ['+'] + signs # --> ['+', '+', '-'] # use if else , list comprehension build derived list of numerical signs numericalsigns = [-1 if each == '-' else 1 each in signs] # --> [1, 1, -1] # use zip combine 2 separate lists single list of pairs (tuples) pairs = list(zip(digits, numericalsigns)) # --> [(4, 1), (5, 1), (1, -1)] # use list comprehension multiple each tuple signeddigits = [digit * sign digit, sign in pairs] # --> [4, 5, -1] # use sum builtin add them sum(signeddigits) # --> 8
Comments
Post a Comment