a +b ?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Jun 11 11:57:55 EDT 2010


On Fri, 11 Jun 2010 22:11:26 +0800, yanhua wrote:

> hi,all!
> it's a simple question:
> input two integers A and B in a line,output A+B?
> 
> this is my program:
> s = input()
> t = s.split()
> a = int(t[0])
> b = int(t[1])
> print(a+b)
> 
> but i think it's too complex,can anybody tell to slove it with less
> code.


Why do you think it is too complex? That seems fine to me. If anything, 
it is too SIMPLE -- where is the error checking? What if the user only 
enters one number? Or three numbers? Or something that isn't a number at 
all?

You can't get much simpler than your code -- you take a string, split it, 
convert the parts into integers, and print the sum. That is very simple. 
Compare it to this solution posted earlier:

(Python 2.x code)
import operator
print reduce(operator.add, map(int, raw_input().split()))

Look at how complex that is! You need to import a module, create a list 
using map, look up the 'add' attribute on the module, then call reduce on 
the list. Try explaining that to a new programmer who isn't familiar with 
map and reduce. And can you imagine how much extra work the computer has 
to do just to save a couple of lines of code?

No, I think your code is very simple. You can save a few lines by writing 
it like this:

s = input('enter two numbers: ')
t = s.split()
print(int(t[0]) + int(t[1]))  # no need for temporary variables a and b

but this still has the problem that there is no error checking for bad 
user input. Fortunately this is Python, where bad input will just raise 
an exception instead of causing a core dump, but still, this is too 
simple for anything except quick-and-dirty scripts.



-- 
Steven



More information about the Python-list mailing list