Re: Reversing a string

2007-07-05 Thread Martin Durkin
[EMAIL PROTECTED] (Alex Martelli) wrote in
news:[EMAIL PROTECTED]: 

> Aahz <[EMAIL PROTECTED]> wrote:
>> I would agree with people who claim
>> that you should memorize most of the built-in functions (which is
>> precisely why there is a high barrier to adding more built-in
>> functions). 
> 
> I think the built-in functions and types a beginner is likely to need
> are a "fuzzy subset" (the decision of whether to include or exclude
> something being not really obvious:-) roughly including:
> 
> abs all any bool chr cmp dict dir enumerate float getattr help hex int
> iter len list max min object open ord property raw_input reversed set
> sorted str sum tuple unichr unicode xrange zip
> 

Thanks guys, that is helpful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-05 Thread Sion Arrowsmith
Jan Vorwerk  <[EMAIL PROTECTED]> wrote:
> [ lots of sensible stuff to discover "reversed" ]
> >>> print reversed.__doc__

See also:
>>> help(reversed)

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Reversing a string

2007-07-04 Thread Jan Vorwerk
Martin Durkin a écrit , le 02.07.2007 06:38:
> This is an interesting point to me. I am just learning Python and I 
> wonder how I would know that a built in function already exists? 
> At what point do I stop searching for a ready made solution to a 
> particular problem and start programming my own function?
> Is it just a matter of reading *all* the documentation before I start 
> coding?

The answer from another beginner like me is: dir()

Try it out interactively (my example with Python 2.4):

---
 >>> dir()
['__builtins__', '__doc__', '__name__']

 >>> __builtins__


 >>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 
'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'IOError', 
'ImportError', 'IndentationError', 'IndexError', 'KeyError', 
'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 
'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 
'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError', 
'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 
'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 
'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 
'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', 
'__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 
'basestring', 'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp', 
'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 
'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 
'file', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 
'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 
'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 
'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 
'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 
'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 
'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

 >>> reversed


 >>> dir(reversed)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', 
'__init__', '__iter__', '__len__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__str__', 'next']

 >>> print reversed.__doc__
reversed(sequence) -> reverse iterator over values of the sequence

Return a reverse iterator

---
Far from me the idea that manuals are useless, but this is a nice thing 
about Python that you can look at what is available interactively.

Cheers
Jan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-04 Thread Alex Martelli
Aahz <[EMAIL PROTECTED]> wrote:
   ...
> This works in all versions of Python back to 1.5.2 IIRC.  reversed() is
> a moderately new built-in function;

Yep: it came with Python 2.4, first alpha just 4 years ago, final
release about 3 years and 8 months ago.  "Moderately new" seems an
appropriate tag.

> I would agree with people who claim
> that you should memorize most of the built-in functions (which is
> precisely why there is a high barrier to adding more built-in functions).

I think the built-in functions and types a beginner is likely to need
are a "fuzzy subset" (the decision of whether to include or exclude
something being not really obvious:-) roughly including:

abs all any bool chr cmp dict dir enumerate float getattr help hex int
iter len list max min object open ord property raw_input reversed set
sorted str sum tuple unichr unicode xrange zip

all reasonably documented at
 .  Of course, as I
mentioned, most inclusions and exclusions may be debatable (why do I
think people need xrange and not necessarily range, set and not
necessarily frozenset, property rather than classmethod, hex more likely
than oct, probably not complex, etc etc).


> But certainly if you're using a datatype you should make a point of
> reading all its documentation, which would mean you'd know that list()
> can convert any iterable type.

Yes, and also the methods and operators of (out of the builtin types I
listed above):

dict float int list open[*] set str tuple unicode

[*] well really file, that's the name of the builtin type, but open is
what one should use as a factory function for it!-)

str and unicode have almost identical methods, save for the big crucial
difference on the semantics of method .translate; float and int also
have the same operators; and tuple has hardly anything, so the learning
task is nowhere as big as it may seem from here:-).


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-04 Thread Aahz
In article <[EMAIL PROTECTED]>,
Martin Durkin  <[EMAIL PROTECTED]> wrote:
>[EMAIL PROTECTED] (Alex Martelli) wrote in
>news:[EMAIL PROTECTED]: 
>>
>> So, something like:
>> 
>> for c in reversed(x): print c
>> 
>> is mostly likely how I'd present the solution to the task. 
>
>This is an interesting point to me. I am just learning Python and
>I wonder how I would know that a built in function already exists?
>At what point do I stop searching for a ready made solution to a
>particular problem and start programming my own function?  Is it just a
>matter of reading *all* the documentation before I start coding?

You should at least know that you can do:

l = list(s)
l.reverse()
for c in l:
print c

This works in all versions of Python back to 1.5.2 IIRC.  reversed() is
a moderately new built-in function; I would agree with people who claim
that you should memorize most of the built-in functions (which is
precisely why there is a high barrier to adding more built-in functions).

But certainly if you're using a datatype you should make a point of
reading all its documentation, which would mean you'd know that list()
can convert any iterable type.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

I support the RKAB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-01 Thread Paul Rubin
Martin Durkin <[EMAIL PROTECTED]> writes:
> Is it just a matter of reading *all* the documentation before I start 
> coding?

It's worth spending an hour or two reading through the library manual,
yes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-01 Thread Martin Durkin
[EMAIL PROTECTED] (Alex Martelli) wrote in
news:[EMAIL PROTECTED]: 

> Martin Durkin <[EMAIL PROTECTED]> wrote:
>...
>> >> def rev(x):
>> >>> mylist = []
>> >>> for char in x:
>> >>>  mylist.append(char)
>> >>> mylist.reverse()
>> >>> for letter in mylist:
>> >>>  print letter
>> >>> 
>> >>> However, compare the incredible difference in clarity and
>> >>> elegance between that and:
>> >>> 
>>  >>> print "\n".join("spam"[::-1])
>...
>> >> OK, maybe I'm missing the point here as I'm new to Python. The
>> >> first one seems clearer to me. What am I missing?
>> >> 
>> > I think all you are missing is familarity with Python, but I too
>> > don't like one-liners simply for their own sake.
>> 
>> I guess that's it. The first one reads more like a textbook example
>> which is about where I am at. Is there any speed benefit from the one
>> liner? 
> 
> The first example reads "excruciatingly low-level" to me: its autor is
> thinking in terms of what the machine is doing, mapped into pretty
> elementary low-level constructs.
> 
sorry you've lost me there.


> 
> So, something like:
> 
> for c in reversed(x): print c
> 
> is mostly likely how I'd present the solution to the task. 

This is an interesting point to me. I am just learning Python and I 
wonder how I would know that a built in function already exists? 
At what point do I stop searching for a ready made solution to a 
particular problem and start programming my own function?
Is it just a matter of reading *all* the documentation before I start 
coding?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-01 Thread Jay Loden

Alex Martelli wrote:
> since what you're doing is...:
> 
 s = "onomatopoeia"
 s = s.join(s[::-1])
 s
> 'aonomatopoeiaionomatopoeiaeonomatopoeiaoonomatopoeiaponomatopoeiaoonoma
> topoeiatonomatopoeiaaonomatopoeiamonomatopoeiaoonomatopoeianonomatopoeia
> o'
> 
> ...which isn't really just reversing the string, but quite a bit more
> work!-)

That's what I get for copying and pasting from the post preceding mine and not 
actually checking it for what it does ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-01 Thread Frank Swarbrick
Alex Martelli wrote:
> Martin Durkin <[EMAIL PROTECTED]> wrote:
>...
> print "\n".join("spam"[::-1])
>...
 OK, maybe I'm missing the point here as I'm new to Python. The first
 one seems clearer to me. What am I missing?

>>> I think all you are missing is familarity with Python, but I too don't
>>> like one-liners simply for their own sake.
>> I guess that's it. The first one reads more like a textbook example which
>> is about where I am at. Is there any speed benefit from the one liner?
> 
> The first example reads "excruciatingly low-level" to me: its autor is
> thinking in terms of what the machine is doing, mapped into pretty
> elementary low-level constructs.
> 
> The second example depends first of all on knowledge of extended-slicing
> (specifically the fact that x[::-1] is a reversal, because of the
> negative -1 "step" aka "stride").  If you don't know about extended
> slicing, you're unlikely to just "get it from context", because it uses
> a syntax based on punctuation rather than readable words whose meaning
> you might guess at.  Python has a modest amount of such "punctuation
> syntax" -- about the same amount as C but definitely more than Cobol
> (where one would typically write "ADD a TO b" to avoid shocking totally
> clueless readers with "mysterious punctuation" such as "a + b"...!!!-).
> Punctuation is often very concise but not "intrinsically obvious" unless
> you've been exposed to it already;-).

Since you mentioned Cobol I couldn't resist...

move "spam" to spam
Display Function Reverse(spam)

There's also slicing (known in Cobol as "reference modification")
move mystring(5:3) to my-newstring
* moves 3 characters starting with character 5

No "negative" slicing, though it could be simulated with Function 
Reverse() and ref.mod.

Frank
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-01 Thread Alex Martelli
Jay Loden <[EMAIL PROTECTED]> wrote:
   ...
> For what it's worth, with python 2.5 on my Macbook:

Hmmm, doesn't look to me as if it's worth much...:

> [EMAIL PROTECTED] jloden]$ python -m timeit 's = "onomatopoeia"; s =
s.join(s[::-1])'

since what you're doing is...:

>>> s = "onomatopoeia"
>>> s = s.join(s[::-1])
>>> s
'aonomatopoeiaionomatopoeiaeonomatopoeiaoonomatopoeiaponomatopoeiaoonoma
topoeiatonomatopoeiaaonomatopoeiamonomatopoeiaoonomatopoeianonomatopoeia
o'
>>>

...which isn't really just reversing the string, but quite a bit more
work!-)


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-01 Thread Alex Martelli
Martin Durkin <[EMAIL PROTECTED]> wrote:
   ...
> >> def rev(x):
> >>> mylist = []
> >>> for char in x:
> >>>  mylist.append(char)
> >>> mylist.reverse()
> >>> for letter in mylist:
> >>>  print letter
> >>> 
> >>> However, compare the incredible difference in clarity and elegance
> >>> between that and:
> >>> 
>  >>> print "\n".join("spam"[::-1])
   ...
> >> OK, maybe I'm missing the point here as I'm new to Python. The first
> >> one seems clearer to me. What am I missing?
> >> 
> > I think all you are missing is familarity with Python, but I too don't
> > like one-liners simply for their own sake.
> 
> I guess that's it. The first one reads more like a textbook example which
> is about where I am at. Is there any speed benefit from the one liner?

The first example reads "excruciatingly low-level" to me: its autor is
thinking in terms of what the machine is doing, mapped into pretty
elementary low-level constructs.

The second example depends first of all on knowledge of extended-slicing
(specifically the fact that x[::-1] is a reversal, because of the
negative -1 "step" aka "stride").  If you don't know about extended
slicing, you're unlikely to just "get it from context", because it uses
a syntax based on punctuation rather than readable words whose meaning
you might guess at.  Python has a modest amount of such "punctuation
syntax" -- about the same amount as C but definitely more than Cobol
(where one would typically write "ADD a TO b" to avoid shocking totally
clueless readers with "mysterious punctuation" such as "a + b"...!!!-).
Punctuation is often very concise but not "intrinsically obvious" unless
you've been exposed to it already;-).

If I was targeting total newbies, since extended slicing is something
that they can well wait a while to learn, I'd probably compromise in
favor of "reversed(x)".  The "reversed" built-in function does basically
the same job as a [::-1] slicing, but any English speaker can probably
guess what it's doing -- presenting a reversed permutation of its
sequence argument.

So, something like:

for c in reversed(x): print c

is mostly likely how I'd present the solution to the task.  Using join
to make a single string is (in this particular case) needlessly
precious, though not really a big deal (and beginners had better learn
about joining pretty early on).  But that definitely does not justify
the excruciating, "micromanaged" nature of the first example, which
uselessly belabors the concept of "reversing" to a silly extent.

Python LETS you program at such lowish levels, if you insist, but it
encourages thinking more about your problem and less about the way the
inner gears of the machine will turn in order to produce a solution for
it...!  Part of the encouragement is indeed that coding at a higher
level of abstraction tends to make your program faster (an "abstraction
reward" to replace the "abstraction penalty" so common with some other
languages:-) -- but clarity and productivity are more important still.


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-01 Thread Jay Loden

Evan Klitzke wrote:
>
>> I guess that's it. The first one reads more like a textbook example which
>> is about where I am at. Is there any speed benefit from the one liner?
> 
> The one line is quite a bit faster:
> 
> [EMAIL PROTECTED] ~ $ python -m timeit 's = "onomatopoeia"; s = 
> s.join(s[::-1])'
> 10 loops, best of 3: 6.24 usec per loop
> 
> [EMAIL PROTECTED] ~ $ python -m timeit '
>> def rev(x):
>> mylist = []
>> for char in x:
>> mylist.append(char)
>> mylist.reverse()
>> return "".join(mylist)
>>
>> s = "onomatopoeia"
>> s = rev(s)'
> 10 loops, best of 3: 9.73 usec per loop


For what it's worth, with python 2.5 on my Macbook:

[EMAIL PROTECTED] jloden]$ python -m timeit 's = "onomatopoeia"; s = 
s.join(s[::-1])'
10 loops, best of 3: 5.2 usec per loop

[EMAIL PROTECTED] jloden]$ python -m timeit ' 
> def rev(x):
>   mylist = list(x)
>   mylist.reverse()
>   return "".join(mylist)
> 
> s = "onomatopoeia"
> s = rev(s)'
10 loops, best of 3: 3.94 usec per loop 

Note that in the second version, I changed the code a little bit so that it no 
longer iterates over every char in the string and instead just calls lis() to 
convert it to a list of chars in order to call list.reverse() on it. 

-Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-01 Thread Evan Klitzke
On 1 Jul 2007 11:09:40 GMT, Martin Durkin <[EMAIL PROTECTED]> wrote:
> Duncan Booth <[EMAIL PROTECTED]> wrote in
> news:[EMAIL PROTECTED]:
>
> > Martin Durkin <[EMAIL PROTECTED]> wrote:
> >
> >> def rev(x):
> >>> mylist = []
> >>> for char in x:
> >>>  mylist.append(char)
> >>> mylist.reverse()
> >>> for letter in mylist:
> >>>  print letter
> >>>
> >>> However, compare the incredible difference in clarity and elegance
> >>> between that and:
> >>>
>  >>> print "\n".join("spam"[::-1])
> >>>
> >>
> >> OK, maybe I'm missing the point here as I'm new to Python. The first
> >> one seems clearer to me. What am I missing?
> >>
> > I think all you are missing is familarity with Python, but I too don't
> > like one-liners simply for their own sake.
> >
>
> I guess that's it. The first one reads more like a textbook example which
> is about where I am at. Is there any speed benefit from the one liner?

The one line is quite a bit faster:

[EMAIL PROTECTED] ~ $ python -m timeit 's = "onomatopoeia"; s = s.join(s[::-1])'
10 loops, best of 3: 6.24 usec per loop

[EMAIL PROTECTED] ~ $ python -m timeit '
> def rev(x):
> mylist = []
> for char in x:
> mylist.append(char)
> mylist.reverse()
> return "".join(mylist)
>
> s = "onomatopoeia"
> s = rev(s)'
10 loops, best of 3: 9.73 usec per loop

-- 
Evan Klitzke <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-01 Thread Stefan Behnel
Martin Durkin wrote:
> Duncan Booth <[EMAIL PROTECTED]> wrote in
> news:[EMAIL PROTECTED]: 
> 
>> Martin Durkin <[EMAIL PROTECTED]> wrote:
>>
>>> def rev(x):
 mylist = []
 for char in x:
  mylist.append(char)
 mylist.reverse()
 for letter in mylist:
  print letter

 However, compare the incredible difference in clarity and elegance
 between that and:

 print "\n".join("spam"[::-1])
>>> OK, maybe I'm missing the point here as I'm new to Python. The first
>>> one seems clearer to me. What am I missing?
>>>
>> I think all you are missing is familarity with Python, but I too don't
>> like one-liners simply for their own sake.
>>
> 
> I guess that's it. The first one reads more like a textbook example which 
> is about where I am at. Is there any speed benefit from the one liner?

Almost definitely. But you can check yourself by using the timeit module.

Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-01 Thread Martin Durkin
Duncan Booth <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Martin Durkin <[EMAIL PROTECTED]> wrote:
> 
>> def rev(x):
>>> mylist = []
>>> for char in x:
>>>  mylist.append(char)
>>> mylist.reverse()
>>> for letter in mylist:
>>>  print letter
>>> 
>>> However, compare the incredible difference in clarity and elegance
>>> between that and:
>>> 
 >>> print "\n".join("spam"[::-1])
>>> 
>> 
>> OK, maybe I'm missing the point here as I'm new to Python. The first
>> one seems clearer to me. What am I missing?
>> 
> I think all you are missing is familarity with Python, but I too don't
> like one-liners simply for their own sake.
> 

I guess that's it. The first one reads more like a textbook example which 
is about where I am at. Is there any speed benefit from the one liner?
thanks
Martin

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-07-01 Thread Duncan Booth
Martin Durkin <[EMAIL PROTECTED]> wrote:

> def rev(x):
>> mylist = []
>> for char in x:
>>  mylist.append(char)
>> mylist.reverse()
>> for letter in mylist:
>>  print letter
>> 
>> However, compare the incredible difference in clarity and elegance
>> between that and:
>> 
>>> >>> print "\n".join("spam"[::-1])
>> 
> 
> OK, maybe I'm missing the point here as I'm new to Python. The first one 
> seems clearer to me. What am I missing?
> 
I think all you are missing is familarity with Python, but I too don't like 
one-liners simply for their own sake.

Slicing is one of Pythons great features, but even experienced programmers 
often forget that you can have a third argument to a slice or that it can 
even be negative.

The syntax for joining a sequence of strings with a separator is ugly, I 
sometimes prefer to write it out as:
   print str.join('\n', whatever)
or:
   joinlines = '\n'.join
   ...
   print joinlines(whatever)

but in this case I'd be as likely to go for an explicit loop for the print:

def rev(x):
for letter in x[::-1]:
print letter

which I think hits about the optimum between brevity and clarity. Your own 
optimum point may of course vary.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-06-30 Thread Martin Durkin
ptn <[EMAIL PROTECTED]> wrote in news:1182997438.541012.54100
@o61g2000hsh.googlegroups.com:

> 
 def rev(x):
> mylist = []
> for char in x:
>  mylist.append(char)
> mylist.reverse()
> for letter in mylist:
>  print letter
> 
> However, compare the incredible difference in clarity and elegance
> between that and:
> 
>> >>> print "\n".join("spam"[::-1])
> 

OK, maybe I'm missing the point here as I'm new to Python. The first one 
seems clearer to me. What am I missing?

Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-06-27 Thread ptn

> mylist = []
>
> That's bad. If you need to use a list in the rev function, you
> should bind a new list to a local variable inside rev.
>

He's right. If you want to use a list to temporarily store the
reversed version of your string, it should exist only in the local
namespace of your function.

There's still stuff you can do with your function to make it work,
such as:

>>> def rev(x):
mylist = []
for char in x:
 mylist.append(char)
mylist.reverse()
for letter in mylist:
 print letter

However, compare the incredible difference in clarity and elegance
between that and:

> >>> print "\n".join("spam"[::-1])

So, big lessons: (1) Global variables suck if you try to manipulate
them and (2) in Python, if your code isn't as clear as you would like,
there's probably a better way to do it.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-06-27 Thread ptn
>
> or one letter per line:
>
> >>> print "\n".join("spam"[::-1])
>
> m
> a
> p
> s
>

One liners rock ;)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-06-27 Thread Neil Cerutti
On 2007-06-27, Scott <[EMAIL PROTECTED]> wrote:
> Yeah I know strings == immutable, but question 1 in section
> 7.14 of "How to think like a computer Scientist" has me trying
> to reverse one.

No, it just wants to to print the characters in reverse, one per
line.

> I've come up with two things, one works almost like it should
> except that every traversal thru the string I've gotten it to
> repeat the "list" again. This is what it looks like:
>
mylist = []

That's bad. If you need to use a list in the rev function, you
should bind a new list to a local variable inside rev.

def rev(x):
> for char in x:
> mylist.append(char)
> mylist.reverse()
> print mylist

Here's an debugging exercise that you should try.

Please explain what you think each line in the above is supposed
to do. Pretend you are trying to convince me that the above
program works correctly. I bet you will see find your errors
right away as a result of this exercise.

> [/code]

> So I figured maybe make it a generator (I'm not TO familiar
> with generators yet so don't laugh) which changed my code just
> a slight bit:

Experimentation with stuff you don't fully understand is a great
way to learn, but not that useful for solving exercises. ;)

-- 
Neil Cerutti
This team is one execution away from being a very good basketball team. --Doc
Rivers
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-06-27 Thread Terry Reedy

"Scott" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Yeah I know strings == immutable, but question 1 in section 7.14 of "How 
to
| think like a computer Scientist" has me trying to reverse one.

>>> 'this is a test'[::-1]
'tset a si siht' 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-06-27 Thread vbr

>  Původní zpráva 
> Od: Will Maier <[EMAIL PROTECTED]>
> Předmět: Re: Reversing a string
> Datum: 27.6.2007 19:08:40
> 
> On Wed, Jun 27, 2007 at 12:53:36PM -0400, Scott wrote:
> > So how on earth would be the best way to: Write a function that
> > takes a string as an argument and outputs the letters backward,
> > one per line.
> 
> >>> def rev(forward):
> ... backward = list(forward)
> ... backward.reverse()
> ... return ''.join(backward)
> >>> rev("spam")
> 'maps'
> 
> list.reverse() changes the list in-place. Instead of iterating over
> the items in the string sequence, you can just convert the input
> string outright.
> 
> -- 
> 
> [Will [EMAIL PROTECTED]|http://www.lfod.us/]
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 

Or using string slice with negative step?

>>> "spam"[::-1]
'maps'

or one letter per line:

>>> print "\n".join("spam"[::-1])
m
a
p
s


Greetings,

Vlastimil Brom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-06-27 Thread Diez B. Roggisch
Scott wrote:

> Yeah I know strings == immutable, but question 1 in section 7.14 of "How
> to think like a computer Scientist" has me trying to reverse one.
> 
> I've come up with two things, one works almost like it should except that
> every traversal thru the string I've gotten it to repeat the "list" again.
> This is what it looks like:
> 
> [code]
mylist = []
def rev(x):
> for char in x:
> mylist.append(char)
> mylist.reverse()
> print mylist
> [/code]



The reverse() is totally useless to apply each when appending each
character. Not only useless, but faulty: if you have a even number of
characters, your string won't be reversed.

All you need to do is this:

>>> x = "abcdefg"
>>> print "".join(reversed(x))
gfedcba


HTH Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-06-27 Thread Stefan Behnel
Scott wrote:
> So how on earth would be the best way to: Write a function that takes a 
> string as an argument and outputs the letters backward, one per line.

Homework?

Anyway, what about:

  for c in string[::-1]:
  print c


Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a string

2007-06-27 Thread Will Maier
On Wed, Jun 27, 2007 at 12:53:36PM -0400, Scott wrote:
> So how on earth would be the best way to: Write a function that
> takes a string as an argument and outputs the letters backward,
> one per line.

>>> def rev(forward):
... backward = list(forward)
... backward.reverse()
... return ''.join(backward)
>>> rev("spam")
'maps'

list.reverse() changes the list in-place. Instead of iterating over
the items in the string sequence, you can just convert the input
string outright.

-- 

[Will [EMAIL PROTECTED]|http://www.lfod.us/]
-- 
http://mail.python.org/mailman/listinfo/python-list


Reversing a string

2007-06-27 Thread Scott
Yeah I know strings == immutable, but question 1 in section 7.14 of "How to 
think like a computer Scientist" has me trying to reverse one.

I've come up with two things, one works almost like it should except that 
every traversal thru the string I've gotten it to repeat the "list" again. 
This is what it looks like:

[code]
>>>mylist = []
>>>def rev(x):
for char in x:
mylist.append(char)
mylist.reverse()
print mylist
[/code]

And the output that sorta works like it should, but threw a curveball, at me 
looks like this:
>>> rev("this is just a test")
['t']
['h', 't']
['i', 't', 'h']
['s', 'h', 't', 'i']
[' ', 'i', 't', 'h', 's']
['i', 's', 'h', 't', 'i', ' ']
['s', ' ', 'i', 't', 'h', 's', 'i']
[' ', 'i', 's', 'h', 't', 'i', ' ', 's']
['j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ']
['u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j']
['s', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u']
['t', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's']
[' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't']
['a', 't', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's', ' ']
[' ', ' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't', 'a']
['t', 'a', 't', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's', ' ', 
' ']
['e', ' ', ' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't', 
'a', 't']
['s', 't', 'a', 't', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's', 
' ', ' ', 'e']
['t', 'e', ' ', ' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 
't', 'a', 't', 's']


So I figured maybe make it a generator (I'm not TO familiar with generators 
yet so don't laugh) which changed my code just a slight bit:

[code]
>>>mylist = []
>>>def rev(x):
for char in x:
mylist.append(char)
mylist.reverse()
yield mylist
[/code]

But even that threw me a curveball:
>>> rev("this is just a test")


So how on earth would be the best way to: Write a function that takes a 
string as an argument and outputs the letters backward, one per line.

It should look like the first char of every list in the top "working" code.

Any help woould be greatly apreciated, and a little bit of explaination as 
to why you did it the way you did would be more helpful than just the code.

Thanks in advance 


-- 
http://mail.python.org/mailman/listinfo/python-list