On 12/03/13 05:57, RJ Ewing wrote:
I am trying to implement rot 13 and am having troubles. My code is as
follows:

There are better ways to do what you are doing but assuming this is a learning exercise rather than a serious project I'll make some comments:

def rot_text(self, s):
   ls = [i for i in s]
   for i in ls:

You could have looped directly over s and built a new list to return.
Just a thought.

       if i.isalpha():
          if i.isupper():

Since the code in the upper and lower sections are nearly identical you can avoid the repetition by assigning the test char (M or m) here and then using a single block to do the conversion.

                test = 'M'
            else:  # must be lower
                test = 'm'

Or more concisely

           test = 'M' if i.isupper() else 'm'


        if i <= test:
          x = ls.index(i)
          ls[x] = chr(ord(i) + 13)
        elif i > test:
          x = ls.index(i)
          ls[x] = chr(ord(i) - 13)

The elif could just as well be an else...

You never used x originally, but then here you do....
but it would have been easier to get it at the start
of the loop with:

for index, char in enumerate(ls):

And that would be more readable names too...

However, given the relatively small character set and fixed target a simple mapping table would be easier to implement as suggested by another poster.

Now if I enter abc, I get nop. But if I enter abcdefghijklmnop, I
get abcqrstuvwxyznop.

No idea what is going on there. But you are returning ls - the list. I would have thought you'd want to return the string version of the list?

return ''.join(ls)

maybe?


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to