473,772 Members | 3,752 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

rot13 in a more Pythonic style?

I'm trying to write rot13, but to do it in a better and more Pythonic
style than I'm currrently using. What would you reckon to the
following pretty ugly thing? How would you improve it? In
particular, I don't like the way a three-way selection is done by
nesting two binary selections. Also I dislike stating the same
algorithm twice, but can't see how to parameterise them neatly.

Yes, I know of .encode() and .translate().
No, I don't actually need rot13 itself, it's just a convenient
substitute example for the real job-specific task.
No, I don't have to do it with lambdas, but it would be nice if the
final function was a lambda.
#!/bin/python
import string

lc_rot13 = lambda c : (chr((ord(c) - ord('a') + 13) % 26 + ord('a')))

uc_rot13 = lambda c : (chr((ord(c) - ord('A') + 13) % 26 + ord('A')))

c_rot13 = lambda c : (((c, uc_rot13(c)) [c in
'ABCDEFGHIJKLMN OPQRSTUVWXYZ']), lc_rot13(c) )[c in
'abcdefghijklmn opqrstuvwxyz']

rot13 = lambda s : string.join([ c_rot13(c) for c in s ],'')
print rot13( 'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt' )

Feb 14 '07 #1
16 2531
You could try "some_string".e ncode('rot_13')

Feb 14 '07 #2
On 2007-02-14, Andy Dingley <di*****@codesm iths.comwrote:
I'm trying to write rot13, but to do it in a better and more
Pythonic style than I'm currrently using. What would you
reckon to the following pretty ugly thing? How would you
improve it? In particular, I don't like the way a three-way
selection is done by nesting two binary selections. Also I
dislike stating the same algorithm twice, but can't see how to
parameterise them neatly.

Yes, I know of .encode() and .translate().
str.translate is what I'd do.

import string
rot13table = string.maketran s(
'abcdefghijklmn opqrstuvwxyzABC DEFGHIJKLMNOPQR STUVWXYZ',
'nopqrstuvwxyza bcdefghijklmNOP QRSTUVWXYZABCDE FGHIJKLM')

print 'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt'.transla te(rot13table)
No, I don't actually need rot13 itself, it's just a convenient
substitute example for the real job-specific task. No, I don't
have to do it with lambdas, but it would be nice if the final
function was a lambda.
How would it being a lambda help you?

--
Neil Cerutti
Feb 14 '07 #3
Andy Dingley wrote:
I'm trying to write rot13, but to do it in a better and more Pythonic
style than I'm currrently using. What would you reckon to the
following pretty ugly thing? How would you improve it? In
particular, I don't like the way a three-way selection is done by
nesting two binary selections. Also I dislike stating the same
algorithm twice, but can't see how to parameterise them neatly.

Yes, I know of .encode() and .translate().
No, I don't actually need rot13 itself, it's just a convenient
substitute example for the real job-specific task.
No, I don't have to do it with lambdas, but it would be nice if the
final function was a lambda.
#!/bin/python
import string

lc_rot13 = lambda c : (chr((ord(c) - ord('a') + 13) % 26 + ord('a')))

uc_rot13 = lambda c : (chr((ord(c) - ord('A') + 13) % 26 + ord('A')))

c_rot13 = lambda c : (((c, uc_rot13(c)) [c in
'ABCDEFGHIJKLMN OPQRSTUVWXYZ']), lc_rot13(c) )[c in
'abcdefghijklmn opqrstuvwxyz']

rot13 = lambda s : string.join([ c_rot13(c) for c in s ],'')
print rot13( 'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt' )
Well first of all, for me (personal) being Pythonic means that I should
separate the logic and variables, in this case there is the rotation
mechanism and the variable with the amount it should rotate.
Then of course the letters case is something I consider as a state of
the letter itself, the meaning of the letter doesn't change.
And being a sucker for dictionaries I use them a lot

So with that in mind I would write a class like this:
###
class Rot(object):
def __init__(self,a mount = 13):
self.__alpha = 'abcdefghijklmn opqrstuvwxyz'
self.__amount = amount
self.__index_st ring = dict()
self.__crypt_in dex_string = dict()
self.__string_i ndex = dict()
self.__crypt_st ring_index = dict()
self.__position = 0

self.__create_d icts()
def __cypher(self,n umber):
alpha_len = len(self.__alph a)
rotation_overfl ow = alpha_len - self.__amount
new_number = None

if number rotation_overfl ow:
new_number = number - self.__amount

else:
new_number = self.__position + self.__amount

return(new_numb er)
def __create_dicts( self):
for letter in self.__alpha:
self.__position += 1

self.__index_st ring[self.__position] = letter
self.__crypt_in dex_string[self.__cypher(s elf.__position)] =
letter

self.__string_i ndex[letter] = self.__position
self.__crypt_st ring_index[letter] =
self.__cypher(s elf.__position)
def encrypt(self,te xt):
text_list = list()
letter_capital = None

for letter in text:
letter_capital = letter.isupper( )
letter = letter.lower()

if letter not in self.__alpha:
text_list.appen d(letter)

else:
position_plain = self.__string_i ndex[letter]
letter_crypt = self.__crypt_in dex_string[position_plain]

if letter_capital:
letter_crypt = letter_crypt.up per()

text_list.appen d(letter_crypt)

return("".join( text_list))
def decrypt(self,te xt):
text_list = list()
letter_capital = None

for letter in text:
letter_capital = letter.isupper( )
letter = letter.lower()

if letter not in self.__alpha:
text_list.appen d(letter)

else:
position_crypt = self.__crypt_st ring_index[letter]
letter_plain = self.__index_st ring[position_crypt]

if letter_capital:
letter_plain = letter_plain.up per()

text_list.appen d(letter_plain)

return("".join( text_list))
###

Testing if it works:
>>rot13.decrypt (rot13.encrypt( "This is a TEST"))
'This is a TEST'

--
mph

Feb 14 '07 #4
On 14 Feb, 16:23, Neil Cerutti <horp...@yahoo. comwrote:
str.translate is what I'd do.
That's what I hope to do too, but it might not be possible (for the
live, complex example). It looks as if I have to make a test, then
process the contents of the code differently depending. There might
well be a translation inside this, but I think I still have to have an
explicit 3-way switch in there.
How would it being a lambda help you?
I'm going to use it in a context where that would make for cleaner
code. There's not much in it though.

I still don't understand what a lambda is _for_ in Python. I know what
they are, I know what the alternatives are, but I still haven't found
an instance where it permits something novel to be done that couldn't
be done otherwise (if maybe not so neatly).

Feb 14 '07 #5
En Wed, 14 Feb 2007 14:04:17 -0300, Andy Dingley <di*****@codesm iths.com>
escribió:
I still don't understand what a lambda is _for_ in Python. I know what
they are, I know what the alternatives are, but I still haven't found
an instance where it permits something novel to be done that couldn't
be done otherwise (if maybe not so neatly).
A lambda is a shorthand for a simple anonymous function. Any lambda can be
written as a function:

lambda args: expression

is the same as:

def __anonymous(arg s): return expression

(but the inverse is not true; lambda only allows a single expression in
the function body).

Except for easy event binding in some GUIs, deferred argument evaluation,
and maybe some other case, the're not used much anyway. Prior common usage
with map and filter can be replaced by list comprehensions (a lot more
clear, and perhaps as fast - any benchmark?)

--
Gabriel Genellina

Feb 14 '07 #6
On Feb 14, 9:04 am, "Andy Dingley" <ding...@codesm iths.comwrote:
I still don't understand what a lambda is _for_ in Python.
Python supports functional programming to a certain extent, and
lambdas are part of this.

http://linuxgazette.net/109/pramode.html
I know what
they are, I know what the alternatives are, but I still haven't found
an instance where it permits something novel to be done that couldn't
be done otherwise (if maybe not so neatly).
Strictly speaking, you can live your whole life without using them.
There's always a procedural way of doing things, as well.

-Beej

Feb 14 '07 #7
"Andy Dingley" <di*****@codesm iths.comwrites:
I'm trying to write rot13, but to do it in a better and more Pythonic
style than I'm currrently using. What would you reckon to the
following pretty ugly thing? How would you improve it? In
particular, I don't like the way a three-way selection is done by
nesting two binary selections. Also I dislike stating the same
algorithm twice, but can't see how to parameterise them neatly.
It looks to me like a good place to use closure and dictionaries.
I would write it this way:

def rot(step):
import string
rot_char = lambda a,c,step=step: chr((((ord(c) - ord(a)) + step) % 26) + ord(a))
make_dict = lambda a,s: dict([(x, rot_char(a, x)) for x in s])
d = make_dict('a', string.ascii_lo wercase)
d.update(make_d ict('A', string.ascii_up percase))
def f(s):
return "".join([d.get(c) or c for c in s])
return f
>>rot13 = rot(13)
rot13('Sybe vk Tenohaqnr, Fcyhaqvt ihe guevtt')
'Florix Grabundae, Splundig vur thrigg'
>>rot_13 = rot(-13)
rot_13('Flori x Grabundae, Splundig vur thrigg')
'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt'

--
HTH,
Rob
Feb 14 '07 #8
"Andy Dingley" <di*****@codesm iths.comwrites:
I'm trying to write rot13, but to do it in a better and more Pythonic
style than I'm currrently using. What would you reckon to the
following pretty ugly thing? How would you improve it? In
particular, I don't like the way a three-way selection is done by
nesting two binary selections. Also I dislike stating the same
algorithm twice, but can't see how to parameterise them neatly.
I'm having a hard time understanding what you're getting at. Why
don't you describe the actual problem instead of the rot13 analogy.
Feb 14 '07 #9
Martin P. Hellwig
for me (personal) being Pythonic means that I should
separate the logic and variables, etc...
Well, for me me Pythonic means using built-in functionalities as much
as possible (like using encode("rot13") or translate), and to write
less code, (avoiding overgeneralizat ions from the start too). It means
other things too.

Bye,
bearophile

Feb 14 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
1535
by: Nickolay Kolev | last post by:
Hi all, I would like to find a more pythonic way of solving the following: Having a string consisting of letters only, find out the total sound score of the string. The sound score is calculated as the sum of the transition scores between the characters in that string. The transition scores are stored in a 26 x 26 matrix. I.e. the transition A -> F would have the score soundScoreMatrix.
15
4492
by: Eirik | last post by:
This is a little function I wrote, inspired by the thread "Urgent HELP! required for Caesar Cipher PLEASE" $ cat /home/keisar/bin/c/ymse/rot13.h char rot13(char character) { int changed; changed = character - 'a' + 'n'; return changed;
5
3296
by: yxq | last post by:
Hello, I want to encrypt and decrypt using ROT13, found a class to encrypt string, but where is the decrypter? http://authors.aspalliance.com/brettb/ROT13EncodingWithASPNet.asp#CodeSamples Thank you
3
1545
by: andrew.fabbro | last post by:
I'm working on an app that will be deployed on several different servers. In each case, I'll want to change some config info (database name, paths, etc.) In perl, I would have done something like this: Package Config; <some exporting mechanics> $dbname = "somename"; etc.
4
1799
by: Carl J. Van Arsdall | last post by:
It seems the more I come to learn about Python as a langauge and the way its used I've come across several discussions where people discuss how to do things using an OO model and then how to design software in a more "Pythonic" way. My question is, should we as python developers be trying to write code that follows more of a python standard or should we try to spend our efforts to stick to a more traditional OO model? For example, in...
20
4211
by: krypto.wizard | last post by:
Is there any editor or IDE in Python (either Windows or Linux) which has very good debugging facilites like MS VisualStudio has or something like that. I like SPE but couldn't easily use winPDP. I need tips to debug my code easily. Every help is greatly appreciated. Thanks
14
3599
by: Pythor | last post by:
I wrote the following code for a personal project. I need a function that will plot a filled circle in a two dimensional array. I found Bresenham's algorithm, and produced this code. Please tell me there's a better way to do this. import numpy def circle(field=None,radius,center=(0,0),value=255,): '''Returns a list of points within 'radius' distance from point 'center'.'''
0
1864
by: robert | last post by:
As more and more python packages are starting to use the bloomy (Java-ish) 'logging' module in a mood of responsibility and as I am not overly happy with the current "thickener" style of usage, I want to put this comment and a alternative most simple default framework for discussion. Maybe there are more Python users which like to see that imported (managed) logging issue more down-to-earth and flexible ? ... Vinay Sajip wrote: >...
11
1393
by: Hussein B | last post by:
Hey, Well, as you all know by now, I'm learning Python :) One thing that is annoying my is the OOP in Python. Consider this code in Java: -- public class Car { private int speed; private String brand; // setters & getters }
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10261
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10104
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9912
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8934
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.