views:

329

answers:

6

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

  1. It does not carry over to strings.
  2. 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?

+4  A: 

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 :)

Roberto Bonvallet
Very nice! Is the first solution more difficult to explain?
Tomaž Pisanski
+1  A: 

Take a look at this discussion.

Mike Cialowicz
+1  A: 

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.

Steven Schlansker
+6  A: 

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:

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'
Anthony Forloney
I was plugging various values for a and b into the statement s = s[a:b:-1] but I am unable to obtain the same effect as s = s[::-1].
Tomaž Pisanski
What values you using for `a` and `b`?
Anthony Forloney
I edited my answer to incorporate `a` and `b` values that will reproduce the same results, hope that helps.
Anthony Forloney
Thanks! I would never have guessed. I did notice that 5 and 6 produce the same results, but None was beyond my abilities, while 0 miserably failed.
Tomaž Pisanski
Yeah 0 does miserably fail, and interesting fact to note that: `None<0` evaluates to `True`
Anthony Forloney
+2  A: 

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.

TheMachineCharmer
I agree with this. If you are trying to teach basic programming concepts using python, then go with the obvious (if non-optimal) way first. Then you can show them the "shortcut" once they understand the theory. (You know, like your math teachers always did? Man that pissed me off :)Then again, if your students already have basic programming skills down and you want to teach them Python specifically, do the slicing method and use it as an opportunity to examine slicing in general and how powerful it can be.
Toji
You should avoid presenting bad code as the first method for anything.
Mike Graham
@Mike Graham: AND present them with code sooo complicated that they lose all the interest before they even get started.Though I am very much aware of pythons strengths OP said he is teaching "Introduction to Computer Programming".
TheMachineCharmer
As you may have guessed it is the first time I am teaching Python. I do have notes from my predecessor, but would like to introduce new concepts in the most efficient sequence. For instance, I introduced immutable types after while loop but before speaking about lists or for loop or range. So I will first show how to reverse a string with while loop and then immediately show the power of stride notation.
Tomaž Pisanski
Having taught programming I can testify that showing them "bad code" that is easy to understand can be a very good start. Just make sure you have enough time in the period to then show them *why* it's not a good way to do it. Some of the "optimal" ways have so much below-the-surface magic going on that it will make their eyes glaze over. Don't let them out of the room without having seen other, better ways of accomplishing the same thing, otherwise the "bad code" sinks in overnight and then you have to dig it out of their brains the next day.
Peter Rowell
@TheMachineCharmer, Teaching an "Introduction to Computer Programming" does not really excuse bad code, or necessitate trying to write C-like code rather than good Python code. The code you posted has quadtratic performance on many implementations and versions of Python, and doesn't really make any clearer what is being done at the level of the metal than do the obvious, clear, Pythonic, O(n) solutions.
Mike Graham
@Peter Rowell, this solution has plenty of below-the-surface magic. It's just longer, less to the point, and potentially less efficient.
Mike Graham
:D I thinks its equally important for students to know `"what bad codes look like"`.
TheMachineCharmer
@Mike Graham: Agreed. I was speaking to the more general idea of using less than optimal solutions to highlight information flow in an algorithm, and then progressing to tighter and tighter implementations, while showing that the same decisions are being made. @TheMachineCharmer: once your class is a little more advanced it can be a lot of fun to put some real howlers up on the board and rip into them. In an *Introduction to Formal Logic* course back in the early 70's we used to dissect Nixon's speeches with a scalpel -- great fun was had by all, except for a few Republicans in the class. :-)
Peter Rowell
@TheMachineCharmer, A valiant goal, but there is plenty of opportunity to see it in the wild and simply is not enough time to scratch the surface of all the bad code that you can write. To paraphrase Tolstoy: *Good code is all alike. All bad code is bad in its own way.*
Mike Graham
@Mike: I am a dinosaur who learned programming in fortran. So my view about "bad code" may be a bit different. I think one should be able to produce the best possible code with the available tools. A real master should be able to hammer a nail in the wall with a notebook if no other tools are available. :-)
Tomaž Pisanski
The best solution always depends on the available resources. I'm a Fortran programmer myself (still!) and try to use it the best I can. Good code to do similar operations in different languages looks dramatically different for obvious reasons, and in a given language good vs. bad code is of course quite subjective.
Mike Graham
+2  A: 

Just ask them a riddle like this:

why

>>> 'dammitimmad'[::-1] == 'dammitimmad'
True

but

>>> 'dammit im mad'[::-1] == 'dammit im mad'
False

?

psihodelia