473,387 Members | 1,561 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

invert or reverse a string... warning this is a rant

Why can't Python have a reverse() function/method like Ruby?

Python:
x = 'a_string'
# Reverse the string
print x[::-1]

Ruby:
x = 'a_string'
# Reverse the string
print x.reverse

The Ruby approach makes sense to me as a human being. The Python
approach is not easy for me (as a human being) to remember. Can that be
changed or should I just start blindly memorizing this stuff?

P.S. I like Python better than Ruby 90% of the time and use Python 90%
of the time, but 10% of the time, little things such as this drive me crazy!
Oct 19 '06 #1
41 3328
rick wrote:
Why can't Python have a reverse() function/method like Ruby?
I'm not steeped enough in daily programming to argue that it isn't
necessary, but my question is why do you need to reverse strings? Is it
something that happens often enough to warrant a method for it?
Oct 19 '06 #2
rick <at*******@vt.eduwrites:
Why can't Python have a reverse() function/method like Ruby?

Python:
x = 'a_string'
# Reverse the string
print x[::-1]

The Ruby approach makes sense to me as a human being. The Python
approach is not easy for me (as a human being) to remember. Can that
be changed or should I just start blindly memorizing this stuff?
You could use:

print ''.join(reversed(x))

That also looks a little bit weird, but it combines well-known Python
idioms straightforwardly.
Oct 19 '06 #3
rick wrote:
The Ruby approach makes sense to me as a human being.
do the humans on your planet spend a lot of time reversing strings?
it's definitely not a very common thing to do over here.

anyway, if you do this a lot, why not define a helper function?

def reverse(s):
return s[::-1]

print reverse("redael ruoy ot em ekat")

</F>

Oct 19 '06 #4
John Salerno wrote:
rick wrote:
>Why can't Python have a reverse() function/method like Ruby?

I'm not steeped enough in daily programming to argue that it isn't
necessary, but my question is why do you need to reverse strings? Is it
something that happens often enough to warrant a method for it?
I'm home for lunch so my email addy is different.

No, it doesn't happen very often, but when I need to reverse something
(usually a list or a string). I can never remember right of the top of
my head how to do so in Python. I always have to Google for an answer or
refer back to old code.

IMO, I should be able to intuitively know how to do this. Python is so
user-friendly most every place else... why can it not be so here?

I wrote this so I'll never have to remember this again:

def invert(invertable_object):
try:
print invertable_object[::-1]
return invertable_object[::-1]
except:
print 'Object not invertable'
return 1

invert([1,2,3,4])
invert('string')
invert({1:2, 3:4})


Oct 19 '06 #5
On 2006-10-19, Brad <rt*****@vt.eduwrote:
I'm home for lunch so my email addy is different.

No, it doesn't happen very often, but when I need to reverse
something (usually a list or a string). I can never remember
right of the top of my head how to do so in Python. I always
have to Google for an answer or refer back to old code.

IMO, I should be able to intuitively know how to do this.
Python is so user-friendly most every place else... why can it
not be so here?

I wrote this so I'll never have to remember this again:

def invert(invertable_object):
try:
print invertable_object[::-1]
return invertable_object[::-1]
except:
print 'Object not invertable'
return 1

invert([1,2,3,4])
invert('string')
invert({1:2, 3:4})
Shoot, now you'll have to remember where in heck you stashed that
function the next time you need to reverse something. ;-)

You'll still be better off in the long run memorizing the slice
notation.

--
Neil Cerutti
Oct 19 '06 #6
Fredrik Lundh wrote:
rick wrote:
>The Ruby approach makes sense to me as a human being.

do the humans on your planet spend a lot of time reversing strings? it's
definitely not a very common thing to do over here.
On our planet, we're all dyslexic. We tend to do things 'backwards' so
being able to easily invert what we do helps the people we show the code
to on your planet make sense of it.
>
anyway, if you do this a lot, why not define a helper function?

def reverse(s):
return s[::-1]

print reverse("redael ruoy ot em ekat")
Thanks, that's what I ended up doing.
Oct 19 '06 #7
John Salerno wrote:
rick wrote:
>Why can't Python have a reverse() function/method like Ruby?


I'm not steeped enough in daily programming to argue that it isn't
necessary, but my question is why do you need to reverse strings?
It would provide symmetry for reversing any sequence (without requiring
an iterator).

(1,2,3).reversed()

"123".reversed()

[1,2,3].reversed()

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Oct 19 '06 #8
James Stroud wrote:
>
It would provide symmetry for reversing any sequence (without requiring
an iterator).

(1,2,3).reversed()

"123".reversed()

[1,2,3].reversed()
That might infuriate those who regard strings as "mischievous"
sequences (ie. things which cause errors because you think you have a
list, but you're actually accessing characters in a string), but it's a
valid point: the built-in sequence types should, within reason, provide
a similar interface.

The proposed solution involving slicing syntax does seem odd in the
sense that it's highly similar to the redundant-for-strings s[:]
operation, and it might require inspiration for anyone looking for
convenience methods on the string object to consider using slicing
instead in this manner. In looking for alternative approaches, I became
somewhat distracted by the classic approach you'd use with certain
functional languages: convert the string into a list of characters (if
it isn't already treated as a list), reverse the list, concatenate the
list. The following requires Python 2.4:

"".join(list(reversed(list(s))))

I guess Python 2.5 has the reversed method of which you speak. Still,
the simplest things are often the best, and Python's classic operators
(indexing, slicing) should always be kept in mind.

Paul

Oct 19 '06 #9
Paul Boddie wrote:
James Stroud wrote:
>>(1,2,3).reversed()

"123".reversed()

[1,2,3].reversed()

I guess Python 2.5 has the reversed method of which you speak.
Not that I could find (as methods of any built in sequence type). 2.5
just has the "reversed" function that returns and iterator and so 2.5
requires these kind of gymnastics on built in sequences:
"".join(list(reversed(list(s))))
Of course, I think str.join can operate on iterators, as Paul Rubin
suggests:
print ''.join(reversed(x))
This latter approach still seems a little clunky, though.

James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Oct 19 '06 #10
James Stroud wrote:
Of course, I think str.join can operate on iterators, as Paul Rubin
suggests:
print ''.join(reversed(x))

This latter approach still seems a little clunky, though.

James
Slices can be named so you could do...
>>reverser = slice(None, None, -1)

'abcdefg'[reverser]
'gfedcba'
Ron
Oct 19 '06 #11
James Stroud wrote:
without requiring an iterator
can we perhaps invent some more arbitrary constraints while we're at it?

</F>

Oct 19 '06 #12
Fredrik Lundh wrote:
James Stroud wrote:
without requiring an iterator

can we perhaps invent some more arbitrary constraints while we're at it?

</F>
Why does it seem to me that you are confusing convienience with
constraint, or are the two equivalent?

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Oct 19 '06 #13
On 2006-10-19, Fredrik Lundh <fr*****@pythonware.comwrote:
James Stroud wrote:
without requiring an iterator

can we perhaps invent some more arbitrary constraints while
we're at it?
No letter G. I don't like them. They wet their nests.

--
Neil Cerutti
You only get a once-in-a-lifetime opportunity so many times.
--Ike Taylor
Oct 19 '06 #14
Fredrik Lundh wrote:
James Stroud wrote:
without requiring an iterator

can we perhaps invent some more arbitrary constraints while we're at it?

</F>
I guess while I'm at it, this thread wouldn't have so much steam were
these idioms seemingly unpythonic:

"".join(reverse(x))
alist[::-1]

The latter, while more terse than alist.reversed(), is unnatural and
ugly compared to the general elegance of other constructs in python.
Were this not the case, beginners and intermediate programmers alike
would not have such trouble remembering it. In fact, the latter's exact
behavior, if I remember correctly, spawned a thread of its own with much
speculation as to the exact meaning of the documentation and whether the
API conformed to this inferred meaning. I'll attempt to provide a link
to the thread if anyone takes me to task on this.

I'm sure many life-long programmers will claim that they have never
created a reverse copy of a data structure for production code, but why
is it that so many jump to the fore to point out that alist[::-1] is how
one produces a reverse copy of a list, or that a string can be reversed
with reversed, join, and an instance of another string (did I leave
something out?)?

But why do so many beginning programmers ask how one might produce a
reverse data structure in python? Perhaps they are just ignorant fools
who don't know that creating a reverse copy of a data structure can be
proven to be a useless operation if only they would stop trying to write
code and begin to write formal proofs. Perhaps their professors are to
blame, unreasonably asking them to write actual code before memorizing
all three+ volumes of Knuth. I'm sure the proof is in there somewhere.

But maybe it is not the purpose of a poweful language like python to be
used as a teaching language. Maybe python should be reserved for use
only by those who have been desensitized to its idiosyncracies,
inconsistencies, and idiomatic workarounds.

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Oct 19 '06 #15
Neil Cerutti wrote:
On 2006-10-19, Fredrik Lundh <fr*****@pythonware.comwrote:
>>James Stroud wrote:

>>>without requiring an iterator

can we perhaps invent some more arbitrary constraints while
we're at it?


No letter G. I don't like them. They wet their nests.
The requirement for an iterator is the constraint. Removin the
requirement for the iterator removes the constraint. Or is the iterator
the convenience?

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Oct 19 '06 #16

JamesI guess while I'm at it, this thread wouldn't have so much steam
Jameswere these idioms seemingly unpythonic:

James "".join(reverse(x))
James alist[::-1]

JamesThe latter, while more terse than alist.reversed(), is unnatural
Jamesand ugly compared to the general elegance of other constructs in
Jamespython. Were this not the case, beginners and intermediate
Jamesprogrammers alike would not have such trouble remembering it.

I've no comment one way or the other on the "".join() idiom. I realize a
lot of folks don't like it. The extended slice notation comes from the
numeric community though where they are probably all former FORTRAN
programmers. I think the concept of start, stop, step (or stride?) is
pretty common there. It also fairly nicely matches the arguments to range()
and extends the list "copy operator" alist[:] in a more-or-less
straightforward fashion. It takes a little getting used to, but it's really
not all that hard to remember once you've seen it a couple times. Besides,
it's not obvious to me that simple sequence slicing would be all that
familiar to the uninitiated.

go-bruins-ly, y'rs,

Skip
Oct 19 '06 #17
On Thu, 19 Oct 2006 12:38:55 -0400, Brad wrote:
John Salerno wrote:
>rick wrote:
>>Why can't Python have a reverse() function/method like Ruby?

I'm not steeped enough in daily programming to argue that it isn't
necessary, but my question is why do you need to reverse strings? Is it
something that happens often enough to warrant a method for it?

I'm home for lunch so my email addy is different.

No, it doesn't happen very often, but when I need to reverse something
(usually a list or a string). I can never remember right of the top of
my head how to do so in Python. I always have to Google for an answer or
refer back to old code.

IMO, I should be able to intuitively know how to do this. Python is so
user-friendly most every place else... why can it not be so here?
I agree -- the reversed() function appears to be an obvious case of purity
overriding practicality :(
>>str(reversed("some string"))
'<reversed object at 0xb7edca4c>'
>>repr(reversed("some string"))
'<reversed object at 0xb7edca4c>'

Not very useful.

The simplest ways to get a reversed string seem to be:
>>"some string"[::-1]
'gnirts emos'
>>''.join(list(reversed("some string")))
'gnirts emos'

neither of which are exactly intuitive, but both are standard Python
idioms.
I wrote this so I'll never have to remember this again:

def invert(invertable_object):
try:
print invertable_object[::-1]
return invertable_object[::-1]
except:
print 'Object not invertable'
return 1
Gah!!! That's *awful* in so many ways.

(1) The name is bad. "invert" is not the same as "reverse". Here's an
invert: 1/2 = 0.5. Your function falsely claims numbers aren't invertable.

(2) Why calculate the reversed object twice?

(3) It is poor practice to have the same function both *print* the result
and *return* the result. What happens when you want the reversed object,
but you don't want it to print? You either write a new function, or you
muck about capturing output and hiding it. You should return the result,
and leave it up to the caller to print if they want to print.

(That's a complaint I have about the dis module -- it prints its results,
instead of returning them as a string. That makes it hard to capture the
output for further analysis.)

(4) Why are you capturing Python's perfectly good and useful traceback,
and printing an unhelpful error message?

(5) Errors should raise exceptions, not return "magic numbers" like 1. 1
is not an error-state, it is perfectly fine output. Now you have to
remember that your invert function returns 1 on error, and calling code
has to check for it:

list_of_reversed_object = []
for obj in list_of_objects_to_reverse:
temp = invert(obj)
if temp == 1:
raise ValueError("invalid object")
# or do something else...
list_of_reversed_objects.append(temp)

Compare:

list_of_reversed_object = []
for obj in list_of_objects_to_reverse:
list_of_reversed_objects.append(invert(obj))
Or if you want to skip invalid objects:

list_of_reversed_object = []
for obj in list_of_objects_to_reverse:
try:
list_of_reversed_objects.append(invert(obj))
except SomeError:
pass

--
Steven.

Oct 19 '06 #18
Steven D'Aprano <st***@REMOVE.THIS.cybersource.com.auwrites:
>''.join(list(reversed("some string")))
'gnirts emos'
''.join(reversed('some string')) should work, without building the
intermediate list.

I generally don't remember the ::-1 syntax so the above would occur to
me sooner.
Oct 19 '06 #19
Steven D'Aprano wrote:
Gah!!! That's *awful* in so many ways.
Thanks... I'm used to hearing encouragement like that. After a while you
begin to believe that everything you do will be awful, so why even
bother trying?

<rant>

It has been my experience that Python has discouraging forums with
someone always calling someone else an idiot or telling them they are
awful in some way. I love Python, but the community is way too negative,
uptight and generally down on users who do not have PhD's in CS or Math.

Do you have children? How would your child feel if he brought you
something he had made and you then told him it was awful in *sooo* many
ways. How does that reflect on you and the community you represent?

Cut people who don't think like you some slack, OK?

</rant>
(1) The name is bad. "invert" is not the same as "reverse". Here's an
invert: 1/2 = 0.5. Your function falsely claims numbers aren't invertable.
Dictionary.com
invert = to reverse in position, order, direction, or relationship.

It matters not that a sequence is thought of as being from left to
right, top to bottom or right to left, does it? Read the sequence as you
normally would (however that may be) and then invert it or read it in
reverse to begin with.

I apologize for bringing this up. Thanks for your time.
Oct 19 '06 #20
At Thursday 19/10/2006 21:07, Brad wrote:
Gah!!! That's *awful* in so many ways.

It has been my experience that Python has discouraging forums with
someone always calling someone else an idiot or telling them they are
awful in some way. I love Python, but the community is way too negative,
uptight and generally down on users who do not have PhD's in CS or Math.
I agree with you being angry.
It's true that our posts are going to stay for a long time, and
people could find and read them, and perhaps copy and use our posted
code. So when something is not up-to-the-standard or not following
the best practices or is not the best way of doing things, that
should be noted.
Certainly there is no need to be rude! Pointing out the deficiencies
and how to avoid them can be done in a kind manner.
But I don't think that "the community" in general is too negative.
It's a lot more "newbie-friendly" than other popular language's.
(1) The name is bad. "invert" is not the same as "reverse". Here's an
invert: 1/2 = 0.5. Your function falsely claims numbers aren't invertable.

Dictionary.com
invert = to reverse in position, order, direction, or relationship.
Note that even on a mathematical sense, "inverse" does not mean only
"multiplicative inverse". -3 is the "additive inverse" of 3, by
example (See <http://mathworld.wolfram.com/AdditiveInverse.html>).
(BTW, integers -except two of them- are not inversible in Z).
So "invert" is not a bad name "per se". But having the reversed()
builtin and reverse() list method implies that a similarly rooted
name would be better (just to be coherent!) - perhaps reversed_string()?
--
Gabriel Genellina
Softlab SRL

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ˇgratis!
ˇAbrí tu cuenta ya! - http://correo.yahoo.com.ar
Oct 20 '06 #21

Brad wrote:
John Salerno wrote:
rick wrote:
Why can't Python have a reverse() function/method like Ruby?
I'm not steeped enough in daily programming to argue that it isn't
necessary, but my question is why do you need to reverse strings? Is it
something that happens often enough to warrant a method for it?

I'm home for lunch so my email addy is different.

No, it doesn't happen very often, but when I need to reverse something
(usually a list or a string). I can never remember right of the top of
my head how to do so in Python. I always have to Google for an answer or
refer back to old code.

IMO, I should be able to intuitively know how to do this. Python is so
user-friendly most every place else... why can it not be so here?

I wrote this so I'll never have to remember this again:

def invert(invertable_object):
try:
print invertable_object[::-1]
return invertable_object[::-1]
except:
print 'Object not invertable'
return 1

invert([1,2,3,4])
invert('string')
invert({1:2, 3:4})
A sequence can be reversed with a .reverse() method. For my needs, in 7
years of programming, I never needed to reverse a string. I think it
sounds like a reasonable rule of thumb to set aside things that you do
fairly often (let's say at least once a week or once in two weeks as
you write code, on average), and make sure you have shortcuts for all
of them, ways to write them quickly and easily, and make it easy to
remember as well. All other things, things you do less often, need not
be done so quickly and easily. Otherwise, I think you'll end up with a
language that has too many built in functions, methods, ins, outs and
what have you's.

If I had to reverse a string I'd first try the reverse method (although
my immediate feeling would be that it's probably not there), and then
I'd use a few lines to make a list, reverse it and join it. I don't
usually use one-liners. I would reason to myself that once in a few
years it's not a hardship to use a couple extra lines of code.

But maybe I'm missing something and in some problem domain there is a
frequent need to reverse a string? I saw your comment about countdown
on a launch of a shuttle, but that's not convincing to me, to be
honest, because if you wished to do anything as you count down (i.e.
print the next second number), you'd just make a loop and you can make
range() command reverse, or you can just reverse the list it returns.

It's a little strange; you do get a feeling that reversing a string
might be useful sometime or other, but the only thing I can think of is
palindromes, as someone else mentioned, which is used in some
textbooks. However, isn't it a little silly to add a function or a
method to language to make each textbook example into a one-liner?

Oct 20 '06 #22
"Brad" <rt*****@vt.eduwrote:

Steven D'Aprano wrote:
Gah!!! That's *awful* in so many ways.

Thanks... I'm used to hearing encouragement like that. After a while you
begin to believe that everything you do will be awful, so why even
bother trying?

<rant>

It has been my experience that Python has discouraging forums with
someone always calling someone else an idiot or telling them they are
awful in some way. I love Python, but the community is way too negative,
uptight and generally down on users who do not have PhD's in CS or Math.

Do you have children? How would your child feel if he brought you
something he had made and you then told him it was awful in *sooo* many
ways. How does that reflect on you and the community you represent?

Cut people who don't think like you some slack, OK?

</rant>
8<---------------------------------------------

This is kind of sad to see - what seems not be appreciated here is the genuine
effort that was put in by Stephen to critique the piece of code - not just a one
liner putdown, but a reasoned exposition, taking time...

and yes - it hurts at first to have your ego bruised - but look past that - and
see the genuine attempt to help.

- Hendrik
Oct 20 '06 #23
I V
On Fri, 20 Oct 2006 09:04:07 +1000, Steven D'Aprano wrote:
I agree -- the reversed() function appears to be an obvious case of purity
overriding practicality :(
>>>str(reversed("some string"))
'<reversed object at 0xb7edca4c>'
>>>repr(reversed("some string"))
'<reversed object at 0xb7edca4c>'
This doesn't seem particularly "pure" to me, either. I would
have thought str(some_iter) should build a string out of the iterator, as
list(some_iter) or dict(some_iter) do. I guess this might have to wait for
Python 3, but str ought to be a proper string constructor, not a "produce
a printable representation of" function, particularly when we have repr to
do the latter.
Oct 20 '06 #24
The Ruby approach makes sense to me as a human being.

http://happyfuncog.blogspot.com/2006...santhrope.html
The Python approach is not easy for me (as a human being) to remember.
I always thought we Pythonistas are already idiots but whenever I meet
a Rubist it ( the human being ) appears completely retarded to me.

Oct 20 '06 #25
"Brad" <rt*****@vt.eduwrote:
Do you have children? How would your child feel if he brought you
something he had made and you then told him it was awful in *sooo* many
ways.
If you're arguing that everything a child does and says should be rewarded,
I seriously doubt that you have any.

(on the other hand, I didn't even have to tell my 3-year old that cutting the
whiskers off the kitten wasn't quite as clever as he had thought; he realized
that all by himself, but a bit too late for the poor animal...)

</F>

Oct 20 '06 #26
Fredrik Lundh wrote:
"Brad" <rt*****@vt.eduwrote:
>Do you have children? How would your child feel if he brought you
something he had made and you then told him it was awful in *sooo* many
ways.

If you're arguing that everything a child does and says should be rewarded...

I'm not arguing that. Only that one should be polite and considerate
when giving advice. That's all.

foo[::-1] is acceptable. So is the helper function that you posted:
def reverse(s):
return s[::-1]
My 2 min hack is awful to some, and I'm OK with that and fully expect
it. But it works OK for me. Is there not room for solutions such as this
in Python?

No hard feelings. Let's close this thread. I'll accept the slicing and
memorize it.

Thanks guys.
Oct 20 '06 #27

I V wrote:
On Fri, 20 Oct 2006 09:04:07 +1000, Steven D'Aprano wrote:
I agree -- the reversed() function appears to be an obvious case of purity
overriding practicality :(
>>str(reversed("some string"))
'<reversed object at 0xb7edca4c>'
>>repr(reversed("some string"))
'<reversed object at 0xb7edca4c>'

This doesn't seem particularly "pure" to me, either. I would
have thought str(some_iter) should build a string out of the iterator, as
list(some_iter) or dict(some_iter) do. I guess this might have to wait for
Python 3, but str ought to be a proper string constructor, not a "produce
a printable representation of" function, particularly when we have repr to
do the latter.
The failing of str(reversed('the string')) caught me off-guard too. I
think you're quite right that it would be good if str() becomes a
proper constructor.

In practice, the short-term fix would be to add a __str__ method to the
'reversed' object, and perhaps to all iterators too (so that trying to
build a string from an iterator would do the obvious thing).

Cheers,

--Tim

Oct 20 '06 #28
Tim N. van der Leeuw wrote:
In practice, the short-term fix would be to add a __str__ method to the
'reversed' object
so what should

str(reversed(range(10)))

do ?
and perhaps to all iterators too (so that trying to build a string from an
iterator would do the obvious thing).
all iterators? who's going to do that?

</F>

Oct 20 '06 #29

sk**@pobox.com wrote:
The extended slice notation comes from the
numeric community though where they are probably all former FORTRAN
programmers. I think the concept of start, stop, step (or stride?) is
pretty common there.
Yep. I do a bit of numerical work and the meaning of abc[::-1] is
plain as day to me.

One thing I'd like to point out is that few people seem to be thrown
off when slices are used to twiddle list elements. A few days back
there was a thread about reordering a list such as [1,2,3,4,5,6,7,8,9]
as [1,4,7,2,5,8,3,6,9], and the advice was along the lines of
a[0::3]+a[1::3]+a[2::3]. I don't remember any complaints about the the
notation there.

I think the problem here isn't the slice notation; it's the use of
slice notation for something that seems conceptually distinct. People
who aren't used to doing a lot of slicing don't always have the
connection between "reversing" and "slicing" in mind. It wouldn't
occur to them to accomplish a reverse with a slice, and it would
surprise them a bit to see it.
Carl

Oct 20 '06 #30

Fredrik Lundh wrote:
Tim N. van der Leeuw wrote:
In practice, the short-term fix would be to add a __str__ method to the
'reversed' object

so what should

str(reversed(range(10)))

do ?
My idea was that reversed.__str__() would do something like the
equivalent of ''.join(reversed(...))

Playing in the interactive shell with that idea I quickly realized that
this would of course consume the iterator as a side-effect... Which is
most likely to be undesirable.

(It works well if you just write it as in the examples above, where the
'reversed' object is temporary and instantly thrown away. But if you
assign the iterator object, in this case 'reversed', to an instance
variable then it should be immediately obvious that having the iterator
consumed as side-effect of calling it's __str__ method is very, very
wrong...)

and perhaps to all iterators too (so that trying to build a string from an
iterator would do the obvious thing).

all iterators? who's going to do that?
It's not as easy as I expected. But if we could come up with a
reasonable way to create a __str__ method for iterators, well who knows
I might give it a go. (It would be my first C code in many years
though)

</F>
Cheers,

--Tim

Oct 20 '06 #31
John Salerno wrote:
I'm not steeped enough in daily programming to argue that it isn't
necessary, but my question is why do you need to reverse strings? Is it
something that happens often enough to warrant a method for it?
String reversal comes in handy when you do palindromes.
--
Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991
================================================== ======================
Oct 20 '06 #32

egbert wrote:
String reversal comes in handy when you do palindromes.
Yes, that's where the big bucks are, the Palindrome Industry.

It is the shortsightedness of the Python core developers that keeps the
palindrome related functions and algorithms out of the standard library

i.

Oct 20 '06 #33

egbertString reversal comes in handy when you do palindromes.

Which would by implication make it handy to have in a CS algorithms class
and not much else. ;-)

Skip

Oct 20 '06 #34
On 20 Oct 2006 09:34:55 -0700, Istvan Albert <is***********@gmail.comwrote:
Yes, that's where the big bucks are, the Palindrome Industry.

It is the shortsightedness of the Python core developers that keeps the
palindrome related functions and algorithms out of the standard library
+1 QOTW

--
Cheers,
Simon B
si***@brunningonline.net
http://www.brunningonline.net/simon/blog/
Oct 20 '06 #35
On Thu, 19 Oct 2006 20:07:27 -0400, Brad wrote:
Steven D'Aprano wrote:
>Gah!!! That's *awful* in so many ways.

Thanks... I'm used to hearing encouragement like that. After a while you
begin to believe that everything you do will be awful, so why even
bother trying?
Well obviously I hit a sore point. I wrote a little hastily, and wasn't
quite as polite as I could have been -- but it is true, the function you
wrote isn't good: a seven line function with five problems with it.

Your function was not at all Pythonic; but it isn't even good style for
any serious programming language I know of. I'm sorry if I came across as
abrasive, but I'm even sorrier that you can't take constructive criticism.
Some techniques are bad practice in any language.

It has been my experience that Python has discouraging forums with
someone always calling someone else an idiot or telling them they are
awful in some way. I love Python, but the community is way too negative,
uptight and generally down on users who do not have PhD's in CS or Math.

Do you have children? How would your child feel if he brought you
something he had made and you then told him it was awful in *sooo* many
ways. How does that reflect on you and the community you represent?
You don't need a PhD to write good code. And do you really want to be
treated as a child?

Perhaps I could/should have sugar-coated my earlier comments, but I've
seen no reason to retract any of them.
--
Steven.

Oct 21 '06 #36
On Thu, 19 Oct 2006 22:22:34 -0300, Gabriel Genellina wrote:

(1) The name is bad. "invert" is not the same as "reverse". Here's an
invert: 1/2 = 0.5. Your function falsely claims numbers aren't
invertable.

Dictionary.com
invert = to reverse in position, order, direction, or relationship.

Note that even on a mathematical sense, "inverse" does not mean only
"multiplicative inverse". -3 is the "additive inverse" of 3, by example
(See <http://mathworld.wolfram.com/AdditiveInverse.html>).
A specialist meaning to invert that even mathematicians don't use unless
they are being explicitly formal.

(BTW,
integers -except two of them- are not inversible in Z).
Is that multiplicative inverse, or additive inverse, or both? (That's a
rhetorical question -- you're obviously talking about multiplicative
inverse, in which case the two integers with inverses are +1 and -1.)

In any case, that would be relevant if the function was for arithmetic in
Z. But it isn't -- it is for reversing sequences. Which supports my
contention that invert is a bad name.

So "invert" is not a bad name "per se".
In ordinary English, "invert" is rarely used for left to right reversal.
(I say "rarely" because there is always somebody who will hammer the
square peg of a word with one meaning into the round hole of a related but
different meaning.) Sometimes (particular in chemistry) is used for
mirror-image reversal, but reversal of a sequence isn't the same as
reflection. (Think of the shapes of the individual character glyphs, or if
you prefer, the bit patterns of the bytes.)

But having the reversed() builtin and reverse()
list method implies that a similarly rooted name would be better (just
to be coherent!) - perhaps reversed_string()?
But it does/shouldn't apply only to strings. What's wrong with just
reverse()?
--
Steven.

Oct 21 '06 #37
Steven D'Aprano wrote:
On Thu, 19 Oct 2006 20:07:27 -0400, Brad wrote:
>Steven D'Aprano wrote:
>>Gah!!! That's *awful* in so many ways.
Thanks... I'm used to hearing encouragement like that. After a while you
begin to believe that everything you do will be awful, so why even
bother trying?

Well obviously I hit a sore point. I wrote a little hastily, and wasn't
quite as polite as I could have been -- but it is true, the function you
wrote isn't good: a seven line function with five problems with it.

Your function was not at all Pythonic; but it isn't even good style for
any serious programming language I know of. I'm sorry if I came across as
abrasive, but I'm even sorrier that you can't take constructive criticism.
Some techniques are bad practice in any language.
Steven, I think just took things a little out of context, and yes you were a bit
overly harsh. But I've also read enough of your post to know you most likely
did not mean any insult either.

Brad's little reminder program was not meant to be actually used in a program as
is of course, but was a small script for him to run so he could see what was
happening visually. Yes, it could be improved on for that purpose too. But for
what it's purpose is, does it really matter that much? It does what he meant it
to do.

Yes, a small dose of politeness, (tactfulness isn't quite the same as suger
coating), always helps when pointing out where others can make improvements
especially while they are still learning their way around.

With that said, If it were me who wrote something that you really thought was
bad, then blast away! ;) (without insulting me of course.) I'd probably take a
second look and agree with you. But I've been programming python since version
2.3 and as a more experienced programmer will appreciate the honest feed back.
[You said from an earlier post...]
(That's a complaint I have about the dis module -- it prints its results,
instead of returning them as a string. That makes it hard to capture the
output for further analysis.)
I have a rewritten version of dis just sitting on my hard disk that fixes
exactly that issue. It needs to be updated to take into account some newer 2.5
features and the tests will need to be updated so they retrieve dis's output
instead of redirecting stdout. If you'd like to finish it up and submit it as a
patch, I can forward it to you. It would be good to have a second set of eyes
look at it also.

Cheers,
Ron
Oct 21 '06 #38
On Fri, 20 Oct 2006 16:17:09 +0200, Fredrik Lundh wrote:
Tim N. van der Leeuw wrote:
>In practice, the short-term fix would be to add a __str__ method to the
'reversed' object

so what should

str(reversed(range(10)))

do ?
The same as str(range(9, -1, -1)) perhaps?

I notice that reversed() already special-cases lists:
>>reversed(tuple(range(5)))
<reversed object at 0xb7c91d0c>
>>reversed("01234")
<reversed object at 0xb7c91b8c>

but:
>>reversed(range(5))
<listreverseiterator object at 0xb7c91b8c>
I'm not sure why it would do such a thing -- something to do with mutable
versus immutable arguments perhaps? It is surprising that x and
reversed(x) aren't the same type. This is even more surprising:
>>list(reversed(range(5)))
[4, 3, 2, 1, 0]
>>tuple(reversed(tuple(range(5))))
(4, 3, 2, 1, 0)

but
>>str(reversed("01234"))
'<reversed object at 0xb7c91b8c>'

It could be argued that people shouldn't be reversing strings with
reversed(), they should use slicing. But I'll argue that "shouldn't" is
too strong a prohibition. Python, in general, prefers named methods and
functions for magic syntax, for many good reasons. (e.g. a str.reverse()
method could have a doc string; str[::-1] can't.) reversed() is designed
to work with sequences, and strings are sequences; it is a recent addition
to the language, not a hold-over from Ancient Days; and since nobody seems
to be arguing that reversed shouldn't be used for other sequence types,
why prohibit strings?

This is not an argument *against* slicing -- obviously slicing is too
fundamental a part of Python to be abandoned. But since reversed() exists,
it should do the right thing. Currently it does the right thing on lists
and tuples, but not on strings.

Perhaps the solution is to special case strings, just like lists are
special cased. Ordinary reversed objects needn't change, but reversed(str)
returns a strreverseiterator that has a __str__ method that does the right
thing. That's just a suggestion, I daresay if it is an awful suggestion
people will tell me soon enough.
--
Steven.

Oct 21 '06 #39
On Sat, 21 Oct 2006 01:58:33 -0500, Ron Adam wrote:
[You said from an earlier post...]
>(That's a complaint I have about the dis module -- it prints its results,
instead of returning them as a string. That makes it hard to capture the
output for further analysis.)

I have a rewritten version of dis just sitting on my hard disk that fixes
exactly that issue. It needs to be updated to take into account some newer 2.5
features and the tests will need to be updated so they retrieve dis's output
instead of redirecting stdout. If you'd like to finish it up and submit it as a
patch, I can forward it to you. It would be good to have a second set of eyes
look at it also.
I'm certainly willing to look at it; as far as submitting it as a patch, I
have no idea what the procedure is. Maybe we can find out together heh? :-)
--
Steven.

Oct 21 '06 #40
Steven D'Aprano wrote:
On Sat, 21 Oct 2006 01:58:33 -0500, Ron Adam wrote:
>[You said from an earlier post...]
>>(That's a complaint I have about the dis module -- it prints its results,
instead of returning them as a string. That makes it hard to capture the
output for further analysis.)
I have a rewritten version of dis just sitting on my hard disk that fixes
exactly that issue. It needs to be updated to take into account some newer 2.5
features and the tests will need to be updated so they retrieve dis's output
instead of redirecting stdout. If you'd like to finish it up and submit it as a
patch, I can forward it to you. It would be good to have a second set of eyes
look at it also.

I'm certainly willing to look at it; as far as submitting it as a patch, I
have no idea what the procedure is. Maybe we can find out together heh? :-)

Sounds good to me. I email an attachment to you. :)
Oct 21 '06 #41
On Thu, 19 Oct 2006 20:07:27 -0400, Brad <rt*****@vt.eduwrote:

>It has been my experience that Python has discouraging forums with
someone always calling someone else an idiot or telling them they are
awful in some way. I love Python, but the community is way too negative,
uptight and generally down on users who do not have PhD's in CS or Math.
>Do you have children? How would your child feel if he brought you
something he had made and you then told him it was awful in *sooo* many
ways. How does that reflect on you and the community you represent?
Wow. Maybe I have thicker skin than you, or perhaps you're a professional
whose self-worth has been damaged, but I would have been grateful for that
critique, not angry. To each his own, I suppose.

DaveM
Oct 23 '06 #42

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Me Padre | last post by:
Hoping someone can help with this. I know I can do this programatically using a loop but I thought there might be some easier or more effective way. I am trying to invert an array. i.e. ...
14
by: ford_desperado | last post by:
Why isn't ALLOW REVERSE SCANS the default? Why do we have to - drop PK - create an index - recreate PK What are the advantages of indexes that do not allow reverse scans?
4
by: Derek Martin | last post by:
Hi List, I have an arraylist of objects. I have created my own IComparable in the object to return the sort on datetime. This works great! Now, I'd like to invert the sort. Currently, it gives...
4
by: kyle.tk | last post by:
I am trying to make a function to reverse a string. What I have right now ends in a segfault. #include <string.h> #include <stdio.h> /* Reverse a string */ void strev(char *s){ char tmp;...
10
by: rtilley | last post by:
s = list('some_random_string') print s s.reverse() print s s = ''.join(s) print s Surely there's a better way to do this, right?
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.