Home > Blockchain >  Python Input with operators and integers
Python Input with operators and integers

Time:02-04

How do I use the map function in python to input 2 integers and 1 operator on the same line like

1 2

I did a, b, c = map(int, input().split())

But it printed Traceback (most recent call last): File "main.py", line 2, in <module> a, b, c = map(int, input().split()) ValueError: invalid literal for int() with base 10: ' '

CodePudding user response:

I might do this:

*ab, c = input().split()
a, b = map(int, ab)

Couldn't help myself, too much fun:

input = lambda: '1 2  '

stack = []
stack  = map(
    lambda s: int(s) if s.isdigit() else stack.pop()   stack.pop(),
    input().split()
)
print(*stack)

Output (Try it online!):

3

CodePudding user response:

The operator module is useful for this.

Create a dictionary that maps the symbols ,-,/,* to their corresponding functions.

Unpack the input to 3 tokens. Call the relevant function (operator).

from operator import add, sub, mul, truediv

OPS = {
    ' ': add,
    '-': sub,
    '/': truediv,
    '*': mul}

x, y, op = input().split() # input must be exactly 3 whitespace separated tokens

print(OPS[op](int(x), int(y)))

This may not be robust as there are no checks to ensure input validity. You may want to change the calls to int() to float()

  • Related