How to teach beginners reversing a string in Python? [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this questionI am teaching a course "Introduction to Computer Programming" to the first year math students. One has to assume that this is the first exposure of students to computer programming. Here are the main goals of my teaching:
- Students should learn and understand the basics of Python.
- Eventually they need to master sufficiently many Python tools so that they are able to select the right tool for a given problem.
- At the same time they have to learn basic skills of problem solving by computer programming.
My method of teaching is to give for each newly introduced concept a series of problems and teasers that motivate students. For instance, when introducing strings and lists a natural question is the task of string or list reversal. If I ask students to write a code that will check whether a string is a palindrome then I better tell them how to reverse it.
For lists, a natural solution myString.reverse()
has at least two drawbacks开发者_开发百科:
- It does not carry over to strings.
- Students will see it a magic unless told about methods first.
The real question is: How should one introduce the problem of reversing a string in Python?
You could teach them about stride notation (::
) first and then slicing and apply both.
s = 'string'
s = s[::-1]
print s # gnirts
References and more information:
- Extended Slices
- An Informal Introduction to Python
- Python string reversed explanation
In response to your comment, you can supply either arguments.
>>> s[len(s):None:-1]
'gnirts'
>>> s[5:None:-1]
'gnirts'
>>> s[::-1] # and of course
'gnirts'
The two obvious ways are:
''.join(reversed(s))
and
s[::-1]
I think both are non-trivial for a programming newbie, but the concepts involved are not really that difficult.
The second way is easier to understand if you start by showing them what the results of s[::3]
, s[::2]
and s[::1]
are. Then s[::-1]
will come naturally :)
Just ask them a riddle like this:
why
>>> 'dammitimmad'[::-1] == 'dammitimmad'
True
but
>>> 'dammit im mad'[::-1] == 'dammit im mad'
False
?
Absolute beginners guide to string reversal in python. ;)
# Tell them that,
# to reverse a string
# we read it backwards
s = 'string' # input string
l = len(s)
rs = '' # reversed string
for i in range(l-1,-1,-1): # range(start,end,step)
rs += s[i]
print rs
But this is not considered pythonic and I am in favor of better methods everyone else have already posted.
Take a look at this discussion.
Introduce them to enough tools (array slicing and perhaps functional-style recursion, in particular) to accomplish the reversal. Then, let them struggle with trying to figure it out for a while. Take a few different answers and compare them, showing the pros and cons of each way.
精彩评论