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

G

Gabriel Genellina

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.
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
 
R

Rainy

Brad said:
John said:
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?
 
H

Hendrik van Rooyen

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
 
I

I V

I agree -- the reversed() function appears to be an obvious case of purity
overriding practicality :(

'<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.
 
F

Fredrik Lundh

Brad said:
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>
 
R

rick

Fredrik said:
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.
 
T

Tim N. van der Leeuw

I said:
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
 
F

Fredrik Lundh

Tim said:
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>
 
C

Carl Banks

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
 
T

Tim N. van der Leeuw

Fredrik said:
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...)

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)


Cheers,

--Tim
 
I

Istvan Albert

egbert said:
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.
 
S

skip

egbert> String 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
 
S

Simon Brunning

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
 
S

Steven D'Aprano

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.
 
S

Steven D'Aprano

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()?
 
D

Dennis Lee Bieber

egbert> String 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. ;-)
But even then... If it is an "algorithm" class, shouldn't one be
learning /how/ to code the loop for comparison, and not just a one-liner
<G>
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
R

Ron Adam

Steven said:
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
 
S

Steven D'Aprano

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 object at 0xb7c91b8c>

but:
<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
'<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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,169
Latest member
ArturoOlne
Top