0

I m having a text , "Remainder 5 when 45 divided by 8"

I just want to assign the division operator ' / ' programmatically to the text "divide" and evaluate 45/ 8 and get the result(Remainder 5) . Thus i verify that the text is correct.

I tried like this...

word= "45 divided by 8"
rep=word.replace('divided by','/')
print(rep)

But i am getting 45 / 8 , not 5 as Remainder

1 Answers1

0

Since it's about translating, a dictionary is a good idea:

translations = {
    'divided by': '//',
    'multiplied by' : '*',
    'times' : '*',
    'seven': '7',
}

def evaluate(sentence):
    for k, v in translations.items():
        sentence = sentence.replace(k, v)
    result = eval(sentence)
    return result

#examples
sentences = [
    "45 divided by 8",
    "45 multiplied by 8",
    "4 times 2 divided by seven",
    "4 times 2 times seven",
]

for s in sentences:
    print(s, 'evaluates to ', evaluate(s))

# displays:
# 45 divided by 8 evaluates to  5
# 45 multiplied by 8 evaluates to  360
# 4 times 2 divided by seven evaluates to  1
# 4 times 2 times seven evaluates to  56

Note that people often recommend ast.literal_eval instead of eval, see e.g. Using python's eval() vs. ast.literal_eval()?

Demi-Lune
  • 1,868
  • 2
  • 15
  • 26