-1
user_input = (int(e) for e in input().split())
a, b, c = user_input

or

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

I wanna know which code above is safe, fast and, efficient for memory usage. please give me your opinions.

Rurou2
  • 167
  • 1
  • 1
  • 7
  • 1
    Does performance actually matter for these? In any case, the first one is more Pythonic, although I personally might convert each variable to an int “manually”. Also, I believe both will throw an error if the result of your split has more than 3 elements. – AMC Jan 11 '20 at 07:12
  • 1
    Second one is equally pythonic. As a matter of fact, `map` would be tiny bit faster. Normally it is okay to use `map` where the function to be mapped is builtin (as is the case here), otherwise you can stick to generator comprehension. However, I agree, if this is the usecase, it does not matter much, except for in the first case you are writing more code without any reason. – Sayandip Dutta Jan 11 '20 at 07:21
  • Memory usage is likely to be same but time will be different. I have added an answer below – Amit Jan 11 '20 at 08:13

2 Answers2

1

For general comparison between comprehension and map see this excellent link at stackoverflow.

You can simulate the input by a random integer and then by running both the codes in a loop 100 thousands times, you will have a tangible performance difference.

Below is the code and its output

import time
import random

random.seed(123)

start_time = time.time()
for i in range(100000):
    a, b, c = (int(e) for e in " ".join([str(random.randint(-10000000,10000000)) for i in range(3)]).split(" "))
end_time = time.time()

print("time taken method 1 is ", end_time - start_time)

start_time = time.time()
for i in range(100000):
    a, b, c = map(int, " ".join([str(random.randint(-10000000,10000000)) for i in range(3)]).split(" "))
end_time = time.time()
print("time taken method 2 is ", end_time - start_time)

Output is

time taken method 1 is  1.182307481765747
time taken method 2 is  1.091458797454834

In this case both are very close but map being a little better. However this little might be crucial for you. You will know better.

Amit
  • 2,018
  • 1
  • 8
  • 12
0

Both are bad. You should process the (very) possible exceptions during the conversion:

try :
    a, b, c = map(int, input().split())
except ValueError :
    sys.exit('Invalid user input')  # etc.
lenik
  • 23,228
  • 4
  • 34
  • 43