473,387 Members | 1,687 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

python challenge question (string manipulation)

Ok, for those who have gotten as far as level 2 (don't laugh!), I have a
question. I did the translation as such:

import string

alphabet = string.lowercase[:26]
code = string.lowercase[2:26] + 'ab'
clue = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc
dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm
jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."

trans = string.maketrans(alphabet, code)
clue = clue.translate(trans)

print clue
raw_input()

It works, but is there a better way to shift the letters of the alphabet
for 'code'? I remember a method that did this for lists, I think, but I
can't remember what it was or if it worked for strings.

Thanks.
Mar 29 '06 #1
8 2235
John Salerno wrote:
It works, but is there a better way to shift the letters of the alphabet
for 'code'? I remember a method that did this for lists, I think, but I
can't remember what it was or if it worked for strings.


Ah ha! This is cleaner:

alphabet = string.ascii_lowercase
code = string.ascii_lowercase[2:] + string.ascii_lowercase[:2]

Yet it still seems kind of verbose. But since that's the official
solution, I guess there's no other way to shift the characters in a string?
Mar 29 '06 #2
John

In python, strings are immutable - you have to create a new string no
matter what you do.

Also, I suspect you meant to say:
alphabet = string.ascii_lowercase
code = alphabet[2:] + alphabet[:2]


I had a similar need recently for a guitar chord generator program I've
been working on. Here is a "shift" function from my utilities module:

def shift(list,num):
'''Shifts sequence "list" by "num" places.
if num is positive, list scrolls forwards,
otherwise, backwards.'''
if abs(num) > len(list):
num=num%len(list) # Use mod to remove full list entry rotations
newlist=list[-num:]+list[:-num]
return newlist

I actually create a new list here, although since lists are mutable, I
could probably just change items in-place. There is very likely
something already in the builtins or the standard library for this, but
I just haven't searched hard enough.

Interesting trap I kept falling into: calling a guitar string a
"string" and then having collisions with the python type of the same
name. Over and over again :)

Regards
Caleb

Mar 29 '06 #3
Caleb Hattingh wrote:
Also, I suspect you meant to say:
alphabet = string.ascii_lowercase
code = alphabet[2:] + alphabet[:2]

Ah yes, I see what you did there. :)
I actually create a new list here, although since lists are mutable, I
could probably just change items in-place. There is very likely
something already in the builtins or the standard library for this, but
I just haven't searched hard enough.

I'm pretty sure I read about a method for moving the items in lists
around like that, so that you can shift the beginning to the end and
vice versa. If I can find it, I'll let you know.
Mar 29 '06 #4
Em Qua, 2006-03-29 Ă*s 19:34 +0000, John Salerno escreveu:
alphabet = string.ascii_lowercase
code = string.ascii_lowercase[2:] + string.ascii_lowercase[:2]

Yet it still seems kind of verbose. But since that's the official
solution, I guess there's no other way to shift the characters in a string?


-----------

from collections import deque
from string import ascii_lowercase

a = deque(ascii_lowercase)
a.rotate(-2)
print list(a)
# prints ['c', 'd', ..., 'z', 'a', 'b']

-----------

But mind the performance! (as an exercise, time the performance of mine
and your approach using the timeit module and post back to the list)

HTH,

--
Felipe.

Mar 29 '06 #5

"John Salerno" <jo******@NOSPAMgmail.com> wrote in message
news:Li******************@news.tufts.edu...
John Salerno wrote:
It works, but is there a better way to shift the letters of the alphabet
for 'code'? I remember a method that did this for lists, I think, but I
can't remember what it was or if it worked for strings.


Ah ha! This is cleaner:

alphabet = string.ascii_lowercase
code = string.ascii_lowercase[2:] + string.ascii_lowercase[:2]

Yet it still seems kind of verbose. But since that's the official
solution, I guess there's no other way to shift the characters in a
string?


The above would look less verbose if the second line 'paid attention' to
the first and were written as the slightly more efficient

code = alphabet[2:] + alphabet[:2]

An alternative is shifted access. alphabet[(i+24)%26]

Terry Jan Reedy


Mar 29 '06 #6
Terry

That is very succint. Rewriting my shift function given earlier:
import string
alpha = string.ascii_lowercase
print alpha abcdefghijklmnopqrstuvwxyz def shift(lst, n): return [lst[(i+len(lst)-n)%len(lst)] for i,item in enumerate(lst)]
print shift(alpha,2)

['y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x']

Shorter and possibly as clear too; thanks!

Keep well
Caleb

Mar 30 '06 #7
Em Qua, 2006-03-29 Ă*s 22:20 -0800, Caleb Hattingh escreveu:
That is very succint. Rewriting my shift function given earlier:
import string
alpha = string.ascii_lowercase
print alpha abcdefghijklmnopqrstuvwxyz def shift(lst, n):

return [lst[(i+len(lst)-n)%len(lst)] for i,item in enumerate(lst)]


It sure is short, but is it fast? Compare to the function below (the
fastest I can think of ATM):

def shift(lst, n):
first = (-n) % len(lst)
result = list(lst[first:]) # if lst is a iterable but not a list
result.extend(lst[:first])
return result

Now benchmarking:

$ python2.4 -mtimeit -s "def shift(lst, n): return [lst[(i+len(lst)-n)%
len(lst)] for i,item in enumerate(lst)]"
"shift('abcdefghijklmnopqrstuvwxyz',2)"
10000 loops, best of 3: 21.5 usec per loop
$ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first =
(-n) % length; result = list(lst[first:]); result.extend(lst[:first]);
return result" "shift('abcdefghijklmnopqrstuvwxyz',2)"
100000 loops, best of 3: 3.98 usec per loop

The five-line version is more than five times faster than the two-line
counterpart. But it scales better too:

$ python2.4 -mtimeit -s "string = 'abcdefghijklmnopqrstuvwxyz'*10000 def
shift(lst, n): length = len(lst); first = (-n) % length; result =
list(lst[first:]); result.extend(lst[:first]); return result"
"shift(string,2)"
100 loops, best of 3: 10.6 msec per loop
$ python2.4 -mtimeit -s "string = 'abcdefghijklmnopqrstuvwxyz'*10000
def shift(lst, n): return [lst[(i+len(lst)-n)%len(lst)] for i,item in
enumerate(lst)]" "shift(string,2)"
10 loops, best of 3: 206 msec per loop

With a 10 000 times larger list it takes almost 20 times less time.

Of course a human can't perceive a 17.52 usec difference in time, but
I'd like to make it clear that the two-line function shouldn't be used
on a real system.

What we learn from this? When it's not needed (like now), please don't
iterate over all items of a list.

HTH,

--
Felipe.

Mar 30 '06 #8
Felipe

I get the same results as you. You make a good point about not
iterating when it's not needed. I played around with your test code
and found some interesting things:

1. enumerate vs. range(len()) has very little overhead (something I
have wondered about)

In my code, making the change causes the timing to go from 27.5 usec to
24.6 usec: basically nothing.

2. I combined the two result statements into one, and your code as
written still appears consistently faster, albeit only slightly:

One-line assignment to result: 6.98; 7.18; 6.49; 7.1 (code below)
Your way via extend: 5.24; 5.26; 5.09; 5.3; 5.26; 5.21 (code further
below)

Is this because of "+" concatenation?

My one-line assignment to result:

[caleb@localhost ~]$ python2.4 -mtimeit -s "def shift(lst, n): length =
len(lst); first =(-n) % length; result = list(lst[first:]) +
list(lst[:first]); return result"
"shift('abcdefghijklmnopqrstuvwxyz',2)" 100000 loops, best of 3: 6.98
usec per loop
[caleb@localhost ~]$ python2.4 -mtimeit -s "def shift(lst, n): length =
len(lst); first =(-n) % length; result = list(lst[first:]) +
list(lst[:first]); return result"
"shift('abcdefghijklmnopqrstuvwxyz',2)"
100000 loops, best of 3: 7.18 usec per loop
[caleb@localhost ~]$ python2.4 -mtimeit -s "def shift(lst, n): length =
len(lst); first =(-n) % length; result = list(lst[first:]) +
list(lst[:first]); return result"
"shift('abcdefghijklmnopqrstuvwxyz',2)"
100000 loops, best of 3: 6.49 usec per loop
[caleb@localhost ~]$ python2.4 -mtimeit -s "def shift(lst, n): length =
len(lst); first =(-n) % length; result = list(lst[first:]) +
list(lst[:first]); return result"
"shift('abcdefghijklmnopqrstuvwxyz',2)"
100000 loops, best of 3: 7.1 usec per loop

Your code:

[caleb@localhost ~]$ python2.4 -mtimeit -s "def shift(lst, n): length =
len(lst); first =(-n) % length; result = list(lst[first:]);
result.extend(lst[:first]); return result"
"shift('abcdefghijklmnopqrstuvwxyz',2)"
100000 loops, best of 3: 5.24 usec per loop
[caleb@localhost ~]$ python2.4 -mtimeit -s "def shift(lst, n): length =
len(lst); first =(-n) % length; result = list(lst[first:]);
result.extend(lst[:first]); return result"
"shift('abcdefghijklmnopqrstuvwxyz',2)"
100000 loops, best of 3: 5.26 usec per loop
[caleb@localhost ~]$ python2.4 -mtimeit -s "def shift(lst, n): length =
len(lst); first =(-n) % length; result = list(lst[first:]);
result.extend(lst[:first]); return result"
"shift('abcdefghijklmnopqrstuvwxyz',2)"
100000 loops, best of 3: 5.09 usec per loop
[caleb@localhost ~]$ python2.4 -mtimeit -s "def shift(lst, n): length =
len(lst); first =(-n) % length; result = list(lst[first:]);
result.extend(lst[:first]); return result"
"shift('abcdefghijklmnopqrstuvwxyz',2)"
100000 loops, best of 3: 5.3 usec per loop
[caleb@localhost ~]$ python2.4 -mtimeit -s "def shift(lst, n): length =
len(lst); first =(-n) % length; result = list(lst[first:]);
result.extend(lst[:first]); return result"
"shift('abcdefghijklmnopqrstuvwxyz',2)"
100000 loops, best of 3: 5.26 usec per loop
[caleb@localhost ~]$ python2.4 -mtimeit -s "def shift(lst, n): length =
len(lst); first =(-n) % length; result = list(lst[first:]);
result.extend(lst[:first]); return result"
"shift('abcdefghijklmnopqrstuvwxyz',2)"
100000 loops, best of 3: 5.21 usec per loop

Caleb

Mar 30 '06 #9

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

Similar topics

63
by: pythonchallenge | last post by:
For the riddles' lovers among you, you are most invited to take part in the Python Challenge, the first python programming riddle on the net. You are invited to take part in it at:...
0
by: pythonchallenge | last post by:
For the riddles' lovers among you, you are most invited to take part in the Python Challenge, the first python programming riddle on the net. You are invited to take part in it at:...
2
by: Andy Leszczynski | last post by:
Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit http://www.pythonchallenge.com/ anybody get to the level 30? :-)
3
by: Magnus Lie Hetland | last post by:
Just saw this on the BBC World program Click Online: http://bbcworld.com/content/template_clickonline.asp?pageid=665&co_pageid=6 I must say, I think this is the first time I've heard Python...
9
by: mjakowlew | last post by:
Hi, I'm trying to use some string manipulation from a file's path. filepath='c:\documents\web\zope\file.ext' I need to extract everthing after the last '\' and save it. I've looked around...
4
by: WaterWalk | last post by:
Hello, I'm currently learning string manipulation. I'm curious about what is the favored way for string manipulation in C, expecially when strings contain non-ASCII characters. For example, if...
0
by: tzotzioy | last post by:
If anyone has a way to contact thesamet, please tell him to check his private messages at the Python Challenge website; I have a couple of ideas for more challenges. Cheers all.
5
by: Niyazi | last post by:
Hi, Does anyone knows any good code for string manipulation similar to RegularExpresion? I might get a value as string in a different format. Example: 20/02/2006 or 20,02,2006 or ...
3
by: crprajan | last post by:
String Manipulation: Given a string like “This is a string”, I want to remove all single characters( alphabets and numerals) like (a, b, 1, 2, .. ) . So the output of the string will be “This is...
3
by: frankeljw | last post by:
I have 2 Java strings 1st String is a series of names, colons, and numbers ie) Name1:13:Name2:4526:Name3:789:Name4:3729:Name5:6:Name6:44 2nd String is a name ie) Name2 I need to get the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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,...
0
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...

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.