-1

So I'm creating a program that gives random outputs including addition, subtraction, multiplication and division. In order to remove repeating any code I am attempting to narrow the function down to essentially

sum(operand)
    a = random.randint(1, 10)
    b = random.randint(1, 10)
    c = a + operand + b
    print c

I am looking to be able to call say sum(*) so c would return the product of a and b. I feel like this is a concatenation issue Here I am using sum as an arbitrary name. The function should be able to add, subtract, multiply and divide, all depending on the operand passed through. For example, if "-" is passed through, c would be a - b, if "/" was passed through, c would be a / b

Thanks

C.Fe.
  • 325
  • 3
  • 11

4 Answers4

2
import random
def operate(a, b, operand):
    return eval(str(a) + operand + str(b))

"operand" is a string. operate(50,5,"*") would return 250, for example.

The eval() function takes a string and executes it. This converts a and b to strings, so in the example given, the resulting string would be "50*5", which would then be executed by eval().

Douglas
  • 1,304
  • 10
  • 26
  • Below the up/downvote buttons, there is an accept button. If an answer is not accepted, people will continue to come to this question thinking that this question possibly has not been given an acceptable answer. – Douglas Dec 06 '16 at 16:31
0

Python:: Turn string into operator

This question basicially asks the same allthough with a different starting point.

From the accepted answer by Annon:

import operator
ops = { "+": operator.add, "-": operator.sub } # etc.

print ops["+"](1,1) # prints 2 

Reference to imported operator class: https://docs.python.org/3.6/library/operator.html

Community
  • 1
  • 1
C.Fe.
  • 325
  • 3
  • 11
0

You can try this:

import random

def produce(func):
    a = random.randint(1, 10)
    b = random.randint(1, 10)
    c = func(a,b)
    return c


def sum(a,b):
    return a+b

def multiply(a,b):
    return a*b

def substract(a,b):
    return a-b

operands = [
            sum,
            multiply,
            substract,
        ]

# tests
print "\n".join(["%s: %d" % ( op.__name__, produce(op) ) for op in operands ])

Sample output:

sum: 14
multiply: 45
substract: 7
Marek Nowaczyk
  • 257
  • 1
  • 5
0

Unified solution (for int numbers, as example) emulating numeric objects and calling __add__, __sub__, __mul__ and floordiv methods:

def do_arith_operation(a, b, op):
    a = int(a).__int__()
    b = int(b).__int__()

    operators = {'+': '__add__', '-': '__sub__', '*': '__mul__', '/': '__floordiv__'}

    return getattr(a, operators[op])(b)


print(do_arith_operation(10, 2, '/'))

The output:

5
  • int(a).__int__() will create an instance of class <class 'int'>
  • __add__, __sub__, __mul__ and floordiv methods: each method takes two objects (the operands of +|-|*|/|) as arguments and returns the result of computation

https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105