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.
this does not work
> 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.
>>> import operator
>>> print reduce(operator.add, map(int, raw_input().split()))
124312 41242
165554
>>>
bye
print sum(int(i) for i in raw_input("Please enter some integers: ").split())
--
Cheers,
Simon B.
--
Have a great day,
Alex (msg sent from GMail website)
meh...@gmail.com; http://www.facebook.com/mehgcap
LOL
> it's a simple question:
> input two integers A and B in a line,output A+B?
>
> this is my program:
> s = input()
input() is probably not what you think it is. Check raw_input instead.
> 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.
print sum(map(int,raw_input().split()))
or replace sum by reduce. BTW, it works with any number of integers
You can find this by walking backwards in your code, starting at a+b,
and generalizing a little bit on your way.
-- Alain.
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
Not that we're playing a round of code golf here, but this is a
slightly nicer take on your version:
one, two = input('enter two numbers: ').split()
print(int(one) + int(two))
I like names over subscripts, but that's just me :)
Fore!
print(sum(map(int, input('enter two numbers: ').split())))
Jean-Paul
Can't beat that for lack of syntax! I'd probably add a check just
because the OP did mention only two int's...
data = [int(i) for i in raw_input('Enter two integers:\n').split()]
if len(data) != 2:
print 'Only enter 2 integers!'
else:
print "\n%d" % sum(data)
Well, I _was_ trying to stick to Steven's more simple map-less form :)
(Although I have to say, I have little sympathy for Steven's
hypothetical "new programmer who isn't familiar with map and reduce".
Python isn't PHP, its built-ins are nowhere near as exhaustive,
something like 80ish vs 2000+ functions? Not exactly a huge lookup
burden.)
I prefer football to golf:
print(sum([sum([(ord(j)-48)*10**pos for pos,j in
enumerate(reversed(i))]) for i in raw_input().split()]))
Geremy Condra
> (Although I have to say, I have little sympathy for Steven's
> hypothetical "new programmer who isn't familiar with map and reduce".
With ‘reduce’ gone in Python 3 [0], I can only interpret that as “I have
little sympathy for programmers who start with Python 3”. Is that in
line with what you meant?
> Python isn't PHP, its built-ins are nowhere near as exhaustive,
> something like 80ish vs 2000+ functions? Not exactly a huge lookup
> burden.)
The process of deprecation (‘map’ and ‘reduce’ are nowadays better
replaced with list comprehensions or generator expressions) surely
entails deprecating learning the deprecated practice for new code.
[0] <URL:http://docs.python.org/py3k/library/functions.html>
--
\ “The fact of your own existence is the most astonishing fact |
`\ you'll ever have to confront. Don't dare ever see your life as |
_o__) boring, monotonous or joyless.” —Richard Dawkins, 2010-03-10 |
Ben Finney
> I have little sympathy for Steven's
> hypothetical "new programmer who isn't familiar with map and reduce".
Perhaps you need to spend some more time helping beginners then, and less
time hanging around Lisp gurus *wink*
> Python isn't PHP, its built-ins are nowhere near as exhaustive,
> something like 80ish vs 2000+ functions? Not exactly a huge lookup
> burden.
It's not the lookup burden, but the mental burden of grasping the idea of
functions-as-data. Higher-order functions (functions that take functions
as data) are notoriously difficult for many people to grasp, and even
some programmers of the calibre of Guido van Rossum never get entirely
comfortable with (e.g.) reduce. That's why Guido recommends people use a
for-loop instead of reduce, apply was removed entirely, and list comps
were introduced as a more friendly alternative to map.
I'm certainly not saying that people should avoid higher-order functional
code, but merely to remember that map and filter aren't introductory
concepts, they're moderately advanced functions that many people find
difficult.
--
Steven
> With ‘reduce’ gone in Python 3 [0]
...
> [0] <URL:http://docs.python.org/py3k/library/functions.html>
It's not gone, it's just resting.
http://docs.python.org/py3k/library/functools.html#functools.reduce
--
Steven
Example uses:
Enter expression: 3+4
7
Enter expression: 1+2+3+4+5
15
Enter expression: 7*18
126
Enter expression: 2**19-1
524287
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
Whoa. This forum is kinda confusing. Where do i ask questions about phytons?
Great threab by the way. :)
-----
[url=http://crosspromotion.wizard4u.com/]joint ventures[/url]
--
View this message in context: http://old.nabble.com/a-%2Bb---tp28855796p28878155.html
Sent from the Python - python-list mailing list archive at Nabble.com.
58 characters. You could remove the space after 'int' to make it 57.
Here's an evil 56-character version...
print(eval(input('enter two numbers: ').replace(*' +')))
--
Mark
.NET from Iron Python anyone?
Regards
Ian
It's pinin' for the fjords.
(sorry ^^)
>
> http://docs.python.org/py3k/library/functools.html#functools.reduce
>
>
Yes, Ben, clearly I was being an asshole here, and my follow up
statement about the small number of built-ins and the ease of looking
up documentation had no bearing on it whatsoever.
When I write in-production code, I write code. I don't write for a
hypothetical first time coder who has no experience with the language.
I don't limit myself to patterns only used in the Python tutorial. If
that means a metaclass or functional style is the right approach, then
that's what I'll use.
If you want to extrapolate that into assumptions on my opinions of the
various Python versions, I obviously can't stop you.
> The process of deprecation (‘map’ and ‘reduce’ are nowadays better
> replaced with list comprehensions or generator expressions) surely
> entails deprecating learning the deprecated practice for new code.
map is still a built-in, it's hardly deprecated. You might want to do
something about that if you insist on everyone conforming to your
ideal style.
I've never used map/reduce outside of Python, this is where I first
encountered it. And I _have_ worked in organisations alongside new
Python coders. That it's easy enough to express both map & reduce in
Python code helped a lot with explaining them.
> I'm certainly not saying that people should avoid higher-order functional
> code, but merely to remember that map and filter aren't introductory
> concepts, they're moderately advanced functions that many people find
> difficult.
And I'm saying that I hope that most people who are professional
developers are capable of learning such advanced functionality, which
they will never do if there are no effective examples for them from
which to learn. I'm not sure why Python's handling of functions is
seen as any more complex than the way it treats everything as first-
class objects. I fear that not encouraging people to explore this
aspect does limit the language's power for them somewhat.
From both Ben & your posts I'm worried that I'm being seen as having
contempt for (at least certain classes of) other developers, when it's
really intended as the contrary.
> Ben Finney <ben+pyt...@benfinney.id.au> wrote:
> > alex23 <wuwe...@gmail.com> writes:
> > > (Although I have to say, I have little sympathy for Steven's
> > > hypothetical "new programmer who isn't familiar with map and
> > > reduce".
> >
> > With ‘reduce’ gone in Python 3 [0], I can only interpret that as “I
> > have little sympathy for programmers who start with Python 3”. Is
> > that in line with what you meant?
>
> Yes, Ben, clearly I was being an asshole here […]
No, it wasn't clear at all. That's why I asked, rather than making
assumptions.
Thanks for clarifying.
--
\ “A thorough reading and understanding of the Bible is the |
`\ surest path to atheism.” —Donald Morgan |
_o__) |
Ben Finney
> And I'm saying that I hope that most people who are professional
> developers are capable of learning such advanced functionality, which
> they will never do if there are no effective examples for them from
> which to learn. I'm not sure why Python's handling of functions is seen
> as any more complex than the way it treats everything as first- class
> objects. I fear that not encouraging people to explore this aspect does
> limit the language's power for them somewhat.
In my experience, some functional tools are truly mind-blowing (at least
they blow *my* mind) but there's nothing difficult about map and reduce.
Some people don't like them, and even seem to fear reduce -- I don't get
that myself, but there you go. However, the first step in understanding
them is to understand that you can use functions as data, and -- again,
this is my experience -- some newcomers to programming have great
difficulty going from this idiom:
code = condition(x)
if code == 0:
return functionA(x)
if code == 1:
return functionB(x)
if code == 2:
return functionC(x)
to this first-class function idiom:
dispatch_table = {0: functionA, 1: functionB, 2: functionC}
code = condition(x)
return dispatch[code](x)
and from that I surmise that they probably would have problems with other
functional forms, such as map, at least at first. Your mileage may vary.
> From both Ben & your posts I'm worried that I'm being seen as having
> contempt for (at least certain classes of) other developers, when it's
> really intended as the contrary.
No implication of contempt was meant. I don't think it's contemptuous to
assume that people will all meet a certain minimum level of experience,
knowledge and general programming skill. Unrealistic, perhaps, but not
contemptuous *grin*
--
Steven
> No, it wasn't clear at all. That's why I asked, rather than making
> assumptions.
>
> Thanks for clarifying.
It should go without saying, but unfortunately the tenor of this forum
has been worsened (temporarily, I hope) by certain interminable threads
of late. So, to be clear:
Thanks for clarifying that you were not expressing the attitude I
inferred.
--
\ “I turned to speak to God/About the world's despair; But to |
`\ make bad matters worse/I found God wasn't there.” —Robert Frost |
_o__) |
Ben Finney
No problem. Thank you for another pleasant exchange.
Ah, crap, I didn't see this until now. I _did_ take the wrong meaning
from it and unfortunately replied accordingly :| So please take this
as a sincere apology (laced with relief that I wasn't anything more
than curt in the response).
I hold some pretty strong views on epistemology and individuals'
capacity for learning which haven't been meshing well with the modest
proposals and crowdsourcing of project work which seems to be taking
up more of this list all the time. So it's probably a good idea to
take a break. A friend has been encouraging me to learn io, so now
might be the time :)
Sorry again, Ben. You're generally one of the more level-header
posters to the list and I should have given you more credit (or
better, just opted not to reply).
Cheers,
alex
> Ben Finney <ben+pyt...@benfinney.id.au> wrote:
> > Thanks for clarifying that you were not expressing the attitude I
> > inferred.
>
> Ah, crap, I didn't see this until now. I _did_ take the wrong meaning
> from it and unfortunately replied accordingly :| So please take this
> as a sincere apology (laced with relief that I wasn't anything more
> than curt in the response).
All's well. I'll raise a glass now for well-tempered discussion to
resume in this forum soon.
--
\ “Our wines leave you nothing to hope for.” —restaurant menu, |
`\ Switzerland |
_o__) |
Ben Finney
And I am not particularly fond of map() and cordially loathe reduce().
Speaking as someone with more than twenty years of programming before
encountering Python more than a decade ago.
--
Aahz (aa...@pythoncraft.com) <*> http://www.pythoncraft.com/
"If you don't know what your program is supposed to do, you'd better not
start writing it." --Dijkstra
"Loathe" is a particularly STRONG world. Are you sure you meant that ?
What in particular do you _not_ enjoy about using
map/reduce (and possibly other functional features of
the Python programing language) ?
--James
Quantification of "experience" is meaningless.
--
--
-- "Problems are solved by method"
Yes, I did mean to use it -- perhaps it is not entirely an accurate
description of my emotional state, but I enjoy the shock effect in this
circumstance.
>What in particular do you _not_ enjoy about using map/reduce (and
>possibly other functional features of the Python programing language) ?
map() never felt particularly Pythonic, especially the way it works with
None as the function combined with multiple arguments. I can't explain
why I loathe reduce() -- it just doesn't fit my brain.
No offense meant, but your "emotional state" has no weight on
the usefulness and effectiveness (or not) of the functional features
of python such as that provided by map() and reduce().
Further: What is "Pythonic" ? This is probably more of a style and
personal taste that might vary from one programmer to another.
I don't recall anywhere in the Python documentation or a Python
document that says map/reduce is or isn't "pythonic" (whatever that means).
Perhaps this list could do without posts pertaining to one's "emotional state".
--James
Pythonic is an ideal, a state of grace that code can achieve which finds
the perfect balance between effectiveness, simplicity, and readability
such that "elegant" is not quite a sufficient word. So a new one had to
be made up.
Its also an acquired taste, in that idiomatic Python takes some growing
on you sometimes.
Its not simply style and personal taste, though certainly there's
something about style and taste involved. Its also about embracing
Python's strengths, avoiding its weaknesses, and just a hint of flair or
sometimes humor.
Consider it an adjective meaning, "Of or related to idealized code
according to the sometimes conflicting Zen of Python and its lesser
known Doctrines of the Bots*. Belief in time travel is required for
proper usage."
As to your question: Of course the docs don't declare what is or is not
pythonic. It is a somewhat shifty goal, as it changes as Python does
(think back into the dark days before comprehensions, where map/reduce
were a lot closer to the ideal).
> Perhaps this list could do without posts pertaining to one's "emotional state".
It could certainly do with a little less 'taking oneself too seriously' :)
--
Stephen Hansen
... Also: Ixokai
... Mail: me+list/python (AT) ixokai (DOT) io
... Blog: http://meh.ixokai.io/
P.S. Python-list was more fun when Timbot was around, and <0.2-ly y'rs>
ing all the time. And discussions between the bots were great.
You do realize my question was completely rhetorical :)
--James
/me withdraws from this discussion :)
My entire response was largely tongue-in-cheek :)
Of course - thank you for that enlightening description of "Pythonic" :)
Hopefully it helps others to understand!
:)
I know :)
Don't you wish there was a "Close Thread" button :)
For the more disgraceful/disgusting threads around here in recent days I
wish there was a "Kill Poster" button. Reminds me of all those jolly
old black and white Hollywood cowboy movies, "we'll have a fair trial,
then we'll hang him" :)
Cheers.
Mark Lawrence.