A suggestion for a possible Python module

Max M maxm at mxm.dk
Tue Mar 4 02:08:24 EST 2003


Erik Max Francis wrote:
> Lance LaDamage wrote:
> 
>>I have noticed that there is one thing that everyone wishes to do in
>>Python
>>... reverse a string.
> 
> Who's everyone?  I can't remember needing desperately to reverse a
> string once in my entire programming life.


argh now you are just being contrary!!!!


My domain name ie. is a palindrome "mxm".

To print this out I could naturally just use the stupid way::

     print 'mxm'

But then I need to hold the superfluos last 'm' in memory.

So a smarter person would obtain memory savings by using the fact that 
it is a palindrome::


     domain_name = 'mx'
     reversed_domain_name = list(domain_name)
     reversed_domain_name.reverse()
     reversed_domain_name = ''.join(reversed_domain_name)
     first_part = domain_name
     last_part = reversed_domain_name[-1:]
     print first_part + last_part


This way I save a whole byte every time I print my domain name!!!!

Had I had an even longer palindrome the savings could potentially have 
been *huge*.

Naturally I have optimised this as a function, so that I can reuse the 
code::


     def the_clever_version_of_mxm_domain_name():
         domain_name = 'mx'
         reversed_domain_name = list(domain_name)
         reversed_domain_name.reverse()
         reversed_domain_name = ''.join(reversed_domain_name)
         first_part = domain_name
         # we only need the last part of palindrome
         last_part = reversed_domain_name[1:]
         return first_part + last_part


It is in a shared module that I can import to save typing and memory in 
all my programs::


     from code_snippets_to_help_save_time_typing_and_memory import \
     the_clever_version_of_mxm_domain_name

     print the_clever_version_of_mxm_domain_name()


So reversing strings is smart, nessecary and important ... see?

-- 

hilsen/regards Max M Rasmussen, Denmark

http://www.futureport.dk/
Fremtiden, videnskab, skeptiscisme og transhumanisme





More information about the Python-list mailing list