Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #34574 > unrolled thread

String manipulation in python..NEED HELP!!!!

Started byqbailey@ihets.org
First post2012-12-10 14:38 -0800
Last post2012-12-11 22:21 +0000
Articles 9 — 9 participants

Back to article view | Back to comp.lang.python


Contents

  String manipulation in python..NEED HELP!!!! qbailey@ihets.org - 2012-12-10 14:38 -0800
    Re: String manipulation in python..NEED HELP!!!! John Gordon <gordon@panix.com> - 2012-12-10 22:59 +0000
      Re: String manipulation in python..NEED HELP!!!! Terry Reedy <tjreedy@udel.edu> - 2012-12-11 14:30 -0500
        Re: String manipulation in python..NEED HELP!!!! Ross Ridge <rridge@csclub.uwaterloo.ca> - 2012-12-11 15:52 -0500
          Re: String manipulation in python..NEED HELP!!!! Tim Delaney <timothy.c.delaney@gmail.com> - 2012-12-12 08:34 +1100
    Re: String manipulation in python..NEED HELP!!!! Vlastimil Brom <vlastimil.brom@gmail.com> - 2012-12-11 00:25 +0100
    Re: String manipulation in python..NEED HELP!!!! Chris Angelico <rosuav@gmail.com> - 2012-12-11 10:36 +1100
    Re: String manipulation in python..NEED HELP!!!! duncan smith <buzzard@invalid.invalid> - 2012-12-11 16:39 +0000
      Re: String manipulation in python..NEED HELP!!!! Peter Pearson <ppearson@nowhere.invalid> - 2012-12-11 22:21 +0000

#34574 — String manipulation in python..NEED HELP!!!!

Fromqbailey@ihets.org
Date2012-12-10 14:38 -0800
SubjectString manipulation in python..NEED HELP!!!!
Message-ID<d6779e35-32b8-417a-abf9-72454573bf56@googlegroups.com>
I need help with a program i am doing. it is a cryptography program. i am given a regular alphabet and a key. i need to use the user input and use the regular alphabet and use the corresponding letter in the key and that becomes the new letter. i have the basic code but need help with how to mainpulate the string to do the encryption/decryption. please help

here is my code so far:


""" crypto.py
    Implements a simple substitution cypher
"""

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key =   "XPMGTDHLYONZBWEARKJUFSCIQV"

def main():
  keepGoing = True
  while keepGoing:
    response = menu()
    if response == "1":
      plain = raw_input("text to be encoded: ")
      print encode(plain)
    elif response == "2":
      coded = raw_input("code to be decyphered: ")
      print decode(coded)
    elif response == "0":
      print "Thanks for doing secret spy stuff with me."
      keepGoing = False
    else:
      print "I don't know what you want to do..."




i really need help on how to encrypt it im not sure how to go about doing that please help.

[toc] | [next] | [standalone]


#34578

FromJohn Gordon <gordon@panix.com>
Date2012-12-10 22:59 +0000
Message-ID<ka5pfp$ge0$1@reader1.panix.com>
In reply to#34574
In <d6779e35-32b8-417a-abf9-72454573bf56@googlegroups.com> qbailey@ihets.org writes:

> """ crypto.py
>     Implements a simple substitution cypher
> """

> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
> key =   "XPMGTDHLYONZBWEARKJUFSCIQV"

> def main():
>   keepGoing = True
>   while keepGoing:
>     response = menu()
>     if response == "1":
>       plain = raw_input("text to be encoded: ")
>       print encode(plain)
>     elif response == "2":
>       coded = raw_input("code to be decyphered: ")
>       print decode(coded)
>     elif response == "0":
>       print "Thanks for doing secret spy stuff with me."
>       keepGoing = False
>     else:
>       print "I don't know what you want to do..."

> i really need help on how to encrypt it im not sure how to go about doing
> that please help.

def encode(plain):
   '''Return a substituted version of the plain text.'''

   encoded = ''

   for ch in plain:
      encoded += key[alpha.index(ch)]

   return encoded

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon@panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"

[toc] | [prev] | [next] | [standalone]


#34637

FromTerry Reedy <tjreedy@udel.edu>
Date2012-12-11 14:30 -0500
Message-ID<mailman.737.1355254259.29569.python-list@python.org>
In reply to#34578
On 12/10/2012 5:59 PM, John Gordon wrote:

> def encode(plain):
>     '''Return a substituted version of the plain text.'''
>     encoded = ''
>     for ch in plain:
>        encoded += key[alpha.index(ch)]
>     return encoded

The turns an O(n) problem into a slow O(n*n) solution. Much better to 
build a list of chars and then join them.

-- 
Terry Jan Reedy

[toc] | [prev] | [next] | [standalone]


#34644

FromRoss Ridge <rridge@csclub.uwaterloo.ca>
Date2012-12-11 15:52 -0500
Message-ID<ka86ee$kdh$1@rumours.uwaterloo.ca>
In reply to#34637
John Gordon wrote:
> def encode(plain):
>     '''Return a substituted version of the plain text.'''
>     encoded = ''
>     for ch in plain:
>        encoded += key[alpha.index(ch)]
>     return encoded

Terry Reedy  <tjreedy@udel.edu> wrote:
>The turns an O(n) problem into a slow O(n*n) solution. Much better to 
>build a list of chars and then join them.

There have been much better suggestions in this thread, but John Gordon's
code above is faster than the equivilent list and join implementation
with Python 2.6 and Python 3.1 (the newest versions I have handy).
CPython optimized this case of string concatenation into O(n) back in
Python 2.4.

					Ross Ridge

-- 
 l/  //	  Ross Ridge -- The Great HTMU
[oo][oo]  rridge@csclub.uwaterloo.ca
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //	  

[toc] | [prev] | [next] | [standalone]


#34649

FromTim Delaney <timothy.c.delaney@gmail.com>
Date2012-12-12 08:34 +1100
Message-ID<mailman.745.1355261688.29569.python-list@python.org>
In reply to#34644

[Multipart message — attachments visible in raw view] — view raw

On 12 December 2012 07:52, Ross Ridge <rridge@csclub.uwaterloo.ca> wrote:

> John Gordon wrote:
> > def encode(plain):
> >     '''Return a substituted version of the plain text.'''
> >     encoded = ''
> >     for ch in plain:
> >        encoded += key[alpha.index(ch)]
> >     return encoded
>
> Terry Reedy  <tjreedy@udel.edu> wrote:
> >The turns an O(n) problem into a slow O(n*n) solution. Much better to
> >build a list of chars and then join them.
>
> There have been much better suggestions in this thread, but John Gordon's
> code above is faster than the equivilent list and join implementation
> with Python 2.6 and Python 3.1 (the newest versions I have handy).
> CPython optimized this case of string concatenation into O(n) back in
> Python 2.4.
>

>From "What's New in Python 2.4":
http://docs.python.org/release/2.4.4/whatsnew/node12.html#SECTION0001210000000000000000

String concatenations in statements of the form s = s + "abc" and s +=
"abc" are now performed more efficiently *in certain circumstances*. This
optimization *won't be present in other Python implementations such as
Jython*, so you shouldn't rely on it; using the join() method of strings is
still recommended when you want to efficiently glue a large number of
strings together.

Emphasis mine.

The optimisation was added to improve the situation for programs that were
already using the anti-pattern of string concatenation, not to encourage
people to use it.

As a real-world case, a bug was recently found in Mercurial where an
operation on Windows was taking orders of magnitudes longer than on
Linux due to use of string concatenation rather than the join idiom (from
~12 seconds spent on string concatenation to effectively zero).

Tim Delaney

[toc] | [prev] | [next] | [standalone]


#34580

FromVlastimil Brom <vlastimil.brom@gmail.com>
Date2012-12-11 00:25 +0100
Message-ID<mailman.692.1355181961.29569.python-list@python.org>
In reply to#34574
2012/12/10  <qbailey@ihets.org>:
> I need help with a program i am doing. it is a cryptography program. i am given a regular alphabet and a key. i need to use the user input and use the regular alphabet and use the corresponding letter in the key and that becomes the new letter. i have the basic code but need help with how to mainpulate the string to do the encryption/decryption. please help
>
> here is my code so far:
>
>
> """ crypto.py
>     Implements a simple substitution cypher
> """
>
> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
> key =   "XPMGTDHLYONZBWEARKJUFSCIQV"
>
> def main():
>   keepGoing = True
>   while keepGoing:
>     response = menu()
>     if response == "1":
>       plain = raw_input("text to be encoded: ")
>       print encode(plain)
>     elif response == "2":
>       coded = raw_input("code to be decyphered: ")
>       print decode(coded)
>     elif response == "0":
>       print "Thanks for doing secret spy stuff with me."
>       keepGoing = False
>     else:
>       print "I don't know what you want to do..."
>
>
>
>
> i really need help on how to encrypt it im not sure how to go about doing that please help.
> --
> http://mail.python.org/mailman/listinfo/python-list


Hi,
if I understand correctly, for the data shown in the code, you may
probably use the translate method of the string (and the corresponding
maketrans method);
cf.:

python 2.7
>>> import string
>>> "ABCDEF...VWXYZ".translate(string.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "XPMGTDHLYONZBWEARKJUFSCIQV"))
'XPMGTD...SCIQV'
>>>


python 3.2
>>> "ABCDEF...VWXYZ".translate("".maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "XPMGTDHLYONZBWEARKJUFSCIQV"))
'XPMGTD...SCIQV'
>>>

hth,
  vbr

[toc] | [prev] | [next] | [standalone]


#34581

FromChris Angelico <rosuav@gmail.com>
Date2012-12-11 10:36 +1100
Message-ID<mailman.693.1355182575.29569.python-list@python.org>
In reply to#34574
On Tue, Dec 11, 2012 at 9:38 AM,  <qbailey@ihets.org> wrote:
> I need help with a program i am doing. it is a cryptography program. i am given a regular alphabet and a key. i need to use the user input and use the regular alphabet and use the corresponding letter in the key and that becomes the new letter. i have the basic code but need help with how to mainpulate the string to do the encryption/decryption. please help

A few starting tips. Firstly, I'm going to assume here that this is a
homework question; you haven't said so, but it seems rather more
likely than the alternative (that you're actually going to use such an
incredibly low-grade cipher and an interactive prompt like this).
Please be honest about this; it's okay to ask for help, but we're not
here to do your homework for you. (We do NOT want to help you to get a
certificate you don't merit, then get a job using that certificate,
and then write code that we'll be staring at in our next jobs. There
are already more than enough incompetent programmers in the world; I'd
rather that you either learn the material for real, or if you can't,
fail the course honestly. Sorry if that sounds harsh, but I'm sure
you'd rather that I didn't have a certificate entitling me to drive a
truck on roads near you/your kids, because I do not know how to drive
one safely.)

Secondly, putting "NEED HELP" in your subject line doesn't, in fact,
help. :) It just makes you sound demanding.

So! On to the actual problem. What you need to do is find the letter
that corresponds to the one you have. Decryption is the same as
encryption but with the "alpha" and "key" switched, so I recommend
creating a function that accepts those two as arguments - something
like this:

clear = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "XPMGTDHLYONZBWEARKJUFSCIQV"

def crypt(msg,from,to):
    # and put your code in here

# To encrypt:
encrypted = crypt(original, clear, key)

# To decrypt:
message = crypt(encrypted, key, clear)

The details of the encryption you can put together from John's and/or
vbr's responses, but make sure you understand the code yourself. For
example: What will each of them do with any non-alphabetic characters?
Suppose your original message is "HELLO, WORLD!" - what will happen to
the comma, space, and exclamation mark? Be sure you know *why* this is
how it is, too.

If you run into trouble, post your non-working code and exactly how
it's not working, and we'll try to help you understand why it's not
working. :) In the meantime, here's a document that you may want to
familiarize yourself with:

http://www.catb.org/esr/faqs/smart-questions.html

It's a great explanation of the how and, more importantly, the why of
asking questions of volunteer geeks.

All the best!

ChrisA

[toc] | [prev] | [next] | [standalone]


#34633

Fromduncan smith <buzzard@invalid.invalid>
Date2012-12-11 16:39 +0000
Message-ID<50c761c6$0$12435$a8266bb1@newsreader.readnews.com>
In reply to#34574
On 10/12/12 22:38, qbailey@ihets.org wrote:
> I need help with a program i am doing. it is a cryptography program. i am given a regular alphabet and a key. i need to use the user input and use the regular alphabet and use the corresponding letter in the key and that becomes the new letter. i have the basic code but need help with how to mainpulate the string to do the encryption/decryption. please help
>
> here is my code so far:
>
>
> """ crypto.py
>      Implements a simple substitution cypher
> """
>
> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
> key =   "XPMGTDHLYONZBWEARKJUFSCIQV"
>
> def main():
>    keepGoing = True
>    while keepGoing:
>      response = menu()
>      if response == "1":
>        plain = raw_input("text to be encoded: ")
>        print encode(plain)
>      elif response == "2":
>        coded = raw_input("code to be decyphered: ")
>        print decode(coded)
>      elif response == "0":
>        print "Thanks for doing secret spy stuff with me."
>        keepGoing = False
>      else:
>        print "I don't know what you want to do..."
>
>
>
>
> i really need help on how to encrypt it im not sure how to go about doing that please help.
>

 >>> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 >>> key = "XPMGTDHLYONZBWEARKJUFSCIQV"
 >>> mapping = {}
 >>> for i, ch in enumerate(alpha):
	mapping[ch] = key[i]

	
 >>> ''.join(mapping[ch] for ch in "ACE")
'XMT'
 >>> ''.join(mapping[ch] for ch in "WORD")
'CEKG'
 >>>


Duncan

[toc] | [prev] | [next] | [standalone]


#34654

FromPeter Pearson <ppearson@nowhere.invalid>
Date2012-12-11 22:21 +0000
Message-ID<aippuuF3grkU1@mid.individual.net>
In reply to#34633
On Tue, 11 Dec 2012 16:39:27 +0000, duncan smith wrote:
[snip]
> >>> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
> >>> key = "XPMGTDHLYONZBWEARKJUFSCIQV"
> >>> mapping = {}
> >>> for i, ch in enumerate(alpha):
> 	mapping[ch] = key[i]

mapping = dict(zip(alpha, key))

-- 
To email me, substitute nowhere->spamcop, invalid->net.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web