How to teach beginners to flip a string in Python?

I teach the course "Introduction to Computer Programming" for first-year students of mathematics. It must be assumed that this is the first publication of students for computer programming. Here are the main goals of my training:

  • Students should learn and understand the basics of Python.
  • In the end, they need to learn enough Python tools so that they can choose the right tool for the problem.
  • At the same time, they should learn basic problem-solving skills using computer programming.

My teaching method is to give each new concept a whole series of problems and teasers that motivate students. For example, when entering strings and lists, the natural question is to search through strings or lists. If I ask students to write code that will check if the string is a palindrome, then I’d better tell them how to cancel it.

For lists, the natural solution myString.reverse() has at least two drawbacks:

  • This does not wrap onto lines.
  • Students will see magic unless they first talk about methods.

The real question is: how should the string reversal problem be introduced in Python?

+4
source share
6 answers

First you can teach them step designations ( :: , and then chop and apply both.

 s = 'string' s = s[::-1] print s # gnirts 

Links and additional information:

In response to your comment, you can specify any arguments.

 >>> s[len(s):None:-1] 'gnirts' >>> s[5:None:-1] 'gnirts' >>> s[::-1] # and of course 'gnirts' 
+7
source

Two obvious ways:

 ''.join(reversed(s)) 

and

 s[::-1] 

I think both are nontrivial for beginners in programming, but the concepts involved are not so difficult.

The second way is easier to understand if you start by displaying their results s[::3] , s[::2] and s[::1] . Then s[::-1] will be natural :)

+4
source

Just ask their riddle like this:

why

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

but

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

?

+3
source

Absolute guide for beginners on string swapping 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 a supporter of the best methods that have still been published.

+2
source

Introduce them into a sufficient number of tools (for example, an array and, in particular, recursion of the functional style) to perform a 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 path.

+1
source

Source: https://habr.com/ru/post/1304024/


All Articles