Issue
I have to write a function which has 2 nested functions inside and computes only sum or difference of as many numbers as we want. Every equation end with "=". I wrote sth like this but it still doesn't work. What I am doing wrong?
def calculator(x: int):
def operation(operator: str):
def calculation(y: int):
while operator != "=":
if operators[i] == "=":
result -= digits[j]
elif operators[i] == "+":
result += digits[j]
else:
break
return result
return operator
return calculator(result)
Function should work like that:
calculator(1)('+')(4)('-')(2)('=')
The result is 3. I can't use any package import or global variables.
Solution
You can also use a dictionary to define your operations, and make a very readable and simple function with space for expansion:
def calc(a: int): return lambda op: {
'+': lambda b: calc(a+b),
'-': lambda b: calc(a-b),
'/': lambda b: calc(a/b),
'*': lambda b: calc(a*b),
}.get(op, a)
print(calc(2)('+')(3)('-')(10)('/')(10)('*')(-100)('='))
Answered By - mama
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.