User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 397,809 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,519 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser:
Views: 3966 | Replies: 19 | Solved
Reply
Join Date: Nov 2006
Posts: 23
Reputation: Haze is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
Haze Haze is offline Offline
Newbie Poster

Question Very basic de/encrypt program

  #1  
Dec 2nd, 2006
when i say basic i mean basic it doesnt store the encrypted string in a file or anything it just prints out what it would be and all i intend it to do is swap a for b, b for c and so on then turn the string round backwards once its done that. and the decrypt would be turinng it round backwards again then changing b to a, c to b etc. anyway i have forgotten how to turn the string round backwards allthough i am pretty sure it has something to do with slicing like
a = pie
b = a[3:0]
print a
print b
with my expetced output being
pie
eip
and with the actual output being
pie
[this is a blank line]
anyway if someone can help with that or if you have a better method that would be great, anyway here is the code.

 #simple encryption program
import os
list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a']
choice = 0
while choice != 2:
os.system("cls")
    print "Encryption/Decryption Program"
    print "-" * 10
    print "0 - Encrypt Text"
    print "1 - Decrypt Text"
    print "2 - Quit"
    choice = input("Choose: ")
    if choice == 0:
        print "Enter the string to be encrypted below"
        text = raw_input()
        for letter in range(1,27):
            letter2 = letter + 1
            text.replace(list[letter], letter2)
        print "Your text encrypted is",text                  
    elif choice == 1:
        print "Enter the string to be decyrpted below"
        text = raw_input()
        for letter in range(27,1):
            letter2 = letter - 1
            text.replace(list[letter], letter2)
        print "Your text decrypted is ",text
    elif choice == 2:
        print "Bye"
    else:
        print "Please enter either 0,1 or 2"
    raw_input()   
#End

The problem is on this line

text.replace(list[letter], letter2)

and the error i get is

Traceback (most recent call last):
File "C:\Python25\Decrypt_Encrypt.py", line 20, in <module>
text.replace(list[letter], letter2)
TypeError: expected a character buffer object

i might just be using the wrong command or syntax or this might just not work at all and iam being a idiot but either way ied like help with this. thanks.
Last edited by Haze : Dec 2nd, 2006 at 12:43 pm.
AddThis Social Bookmark Button
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,414
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 173
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Very basic de/encrypt program

  #2  
Dec 2nd, 2006
Sounds like you want to do a simple swap crypting, something like this?
  1. # simple crypt using a swap of 2 adjoining characters
  2.  
  3. def swap_crypt(str1):
  4. """
  5. this function will encrypt/decrypt a string
  6. """
  7. # change string to a mutable list of characters
  8. list1 = list(str1)
  9. # iterate the list with step=2
  10. for k in range(0, len(list1), 2):
  11. if len(list1) > k + 1:
  12. # do a swap of groups of 2 items each in the list
  13. list1[k], list1[k+1] = list1[k+1], list1[k]
  14. # change list back to a string
  15. return ''.join(list1)
  16.  
  17. str1 = 'love to eat pie'
  18. # encrypt the string
  19. str2 = swap_crypt(str1)
  20.  
  21. print str1 # love to eat pie
  22. print str2 # olevt oae tipe
  23.  
  24. # decrypt the encrypted string
  25. str3 = swap_crypt(str2)
  26.  
  27. print str3 # love to eat pie
Last edited by vegaseat : Dec 2nd, 2006 at 2:57 pm. Reason: tags
May 'the Google' be with you!
Reply With Quote  
Join Date: Nov 2006
Posts: 23
Reputation: Haze is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
Haze Haze is offline Offline
Newbie Poster

Re: Very basic de/encrypt program

  #3  
Dec 2nd, 2006
thanks i guess allthough a explanation as to where my code is going wrong would be good. i should probably have said i probably know nothing about python compared to the average person on these boards. I would like to learn more but my attitude stops me iam to lazy and i lack determination and get frustrated with things quite easy. I like programming i just dont like learning how to program.
Reply With Quote  
Join Date: Jul 2006
Posts: 562
Reputation: jrcagle is on a distinguished road 
Rep Power: 4
Solved Threads: 72
jrcagle jrcagle is offline Offline
Posting Pro

Re: Very basic de/encrypt program

  #4  
Dec 2nd, 2006
Originally Posted by Haze View Post
when i say basic i mean basic it doesnt store the encrypted string in a file or anything it just prints out what it would be and all i intend it to do is swap a for b, b for c and so on then turn the string round backwards once its done that. and the decrypt would be turinng it round backwards again then changing b to a, c to b etc. anyway i have forgotten how to turn the string round backwards allthough i am pretty sure it has something to do with slicing like
a = pie
b = a[3:0]
print a
print b
with my expetced output being
pie
eip
and with the actual output being
pie
[this is a blank line]
anyway if someone can help with that or if you have a better method that would be great, anyway here is the code.

 #simple encryption program
import os
list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a']
choice = 0
while choice != 2:
os.system("cls")
    print "Encryption/Decryption Program"
    print "-" * 10
    print "0 - Encrypt Text"
    print "1 - Decrypt Text"
    print "2 - Quit"
    choice = input("Choose: ")
    if choice == 0:
        print "Enter the string to be encrypted below"
        text = raw_input()
        for letter in range(1,27):
            letter2 = letter + 1
            text.replace(list[letter], letter2)
        print "Your text encrypted is",text                  
    elif choice == 1:
        print "Enter the string to be decyrpted below"
        text = raw_input()
        for letter in range(27,1):
            letter2 = letter - 1
            text.replace(list[letter], letter2)
        print "Your text decrypted is ",text
    elif choice == 2:
        print "Bye"
    else:
        print "Please enter either 0,1 or 2"
    raw_input()   
#End

The problem is on this line

text.replace(list[letter], letter2)

and the error i get is

Traceback (most recent call last):
File "C:\Python25\Decrypt_Encrypt.py", line 20, in <module>
text.replace(list[letter], letter2)
TypeError: expected a character buffer object

i might just be using the wrong command or syntax or this might just not work at all and iam being a idiot but either way ied like help with this. thanks.

Well, several things here (if you don't mind the long explanation):

(1) This caused several problems:

for letter in range(1,27):
             letter2 = letter + 1
             text.replace(list[letter], letter2)

The error you saw happened because you were trying to replace the string 'list[letter]' with an integer 'letter2', which can't work; you have to replace strings with strings. Hence: text.replace(list[letter],list[letter2]) gets rid of that error.

But then, your code ran off the end of list because the highest value for letter2 is going to be 27, but the highest index in list is 26 (check me on those statements). So instead of range(1,27), we want 'range(26)'.

Then after all that, the string still doesn't change. That's because the line 'text.replace(...)' returns the new string, but you don't store the result anywhere. We want 'text = text.replace(...)'

Here's the new section of code:

if choice == 0:
        print "Enter the string to be encrypted below"
        text = raw_input()
        for letter in range(26): # <---
            letter2 = letter + 1
            text = text.replace(list[letter], list[letter2])
        print "Your text encrypted is",text                  
    elif choice == 1:
        print "Enter the string to be decyrpted below"
        text = raw_input()
        for letter in range(26): # <---
            letter2 = letter - 1
            text = text.replace(list[letter], list[letter2])
        print "Your text decrypted is ",text

Having fixed all that, something bad now happens:

Encryption/Decryption Program
----------
0 - Encrypt Text
1 - Decrypt Text
2 - Quit
Choose: 0
Enter the string to be encrypted below
blah
Your text encrypted is aaaa

ACK!

So we walk through the code manually:

for letter in range(26):
    print list[letter], list[letter+1]
    text = text.replace(list[letter], list[letter+1])
    print text

    
a b
blbh
b c
clch
c d
dldh
d e
eleh
e f
flfh
f g
glgh
g h
hlhh
h i
ilii
i j
jljj
j k
klkk
k l
llll
l m
mmmm
m n
nnnn
n o
oooo
o p
pppp
p q
qqqq
q r
rrrr
r s
ssss
s t
tttt
t u
uuuu
u v
vvvv
v w
wwww
w x
xxxx
x y
yyyy
y z
zzzz
z a
aaaa

Oohh... the code replaces each a with b and then each b with c, which causes both 'natural' b's and a's changed into b's to become c's. Eventually, everything becomes an a.

One solution is to walk through the list backwards:

for letter in range(25,-1,-1): # goes from 25 to 0 counting by -1
   letter2 = letter + 1
   text = text.replace(list[letter], list[letter2])

Which gives the results

Encryption/Decryption Program
----------
0 - Encrypt Text
1 - Decrypt Text
2 - Quit
Choose: 0
Enter the string to be encrypted below
blah
Your text encrypted is cmbi

Encryption/Decryption Program
----------
0 - Encrypt Text
1 - Decrypt Text
2 - Quit
Choose: 1
Enter the string to be decyrpted below
cmbi
Your text decrypted is  blah

If you want to reverse a string, the following is good:

rev = s[::-1]

That expression takes a slice from end to beginning, taking characters -1 at a time.

Hope it helps,
Jeff
Reply With Quote  
Join Date: Nov 2006
Posts: 23
Reputation: Haze is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
Haze Haze is offline Offline
Newbie Poster

Re: Very basic de/encrypt program

  #5  
Dec 2nd, 2006
Originally Posted by jrcagle View Post
But then, your code ran off the end of list because the highest value for letter2 is going to be 27, but the highest index in list is 26 (check me on those statements). So instead of range(1,27), we want 'range(26)'.


now thats what a call a explanation :cheesy:. as for the quote above there i think your wrong about that because well heres a example.

for i in range(1,10):
    print i

the output you would expect is just 1 to 10 but its actully 1 to 9. anyway thanks for explaning why my code is completely useless and flawed and in such great detail (this may sound sarcastic but i assure you its not). some of the mistakes i would have figured out myself like not actully assigning it to anything. ill look over the redone code and see how it works.
Reply With Quote  
Join Date: Nov 2006
Posts: 23
Reputation: Haze is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
Haze Haze is offline Offline
Newbie Poster

Re: Very basic de/encrypt program

  #6  
Dec 3rd, 2006
sorry for double posting i cant find the edit button but i have found 1 problem with the program you have given me. when i try to encrpyt 'z' it will come out as b becuase it changes z to a then a to b. it works the same when decrypting the 'b' it comes out as z becuase it changes b to a then a to z.
Reply With Quote  
Join Date: Jul 2006
Posts: 562
Reputation: jrcagle is on a distinguished road 
Rep Power: 4
Solved Threads: 72
jrcagle jrcagle is offline Offline
Posting Pro

Re: Very basic de/encrypt program

  #7  
Dec 3rd, 2006
Originally Posted by Haze View Post
sorry for double posting i cant find the edit button but i have found 1 problem with the program you have given me. when i try to encrpyt 'z' it will come out as b becuase it changes z to a then a to b. it works the same when decrypting the 'b' it comes out as z becuase it changes b to a then a to z.


Oohh. Good testing. Sorry to let that slip through.

Briefly back to this:
But then, your code ran off the end of list because the highest value for letter2 is going to be 27, but the highest index in list is 26 (check me on those statements). So instead of range(1,27), we want 'range(26)'.
for i in range(1,10):
    print i
The output you would expect is just 1 to 10 but its actully 1 to 9.

You're right about your example. The tricky part is that letter2 = letter + 1, so that the highest value of *letter* is 26, so that the highest value of letter2 will be 27.

OK: how to fix the cypher 'z' bug?

I think the real problem is that you process the text 26 times, and the letters get touched 26 times each. So whether you go up or down, something's guaranteed to get mis-encrypted. Further, your algorithm only really works if *all* of the characters go up or down, which doesn't really help when you want to do a random substitution like the Cryptograms in the newspapers.

So: what if you re-wrote your algorithm so that each letter only gets touched once? I'll bet you could do that with a for loop, and maybe the functions ord() and chr().

Jeff
Reply With Quote  
Join Date: Nov 2006
Posts: 23
Reputation: Haze is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
Haze Haze is offline Offline
Newbie Poster

Re: Very basic de/encrypt program

  #8  
Dec 3rd, 2006
Originally Posted by jrcagle View Post
So: what if you re-wrote your algorithm so that each letter only gets touched once? I'll bet you could do that with a for loop, and maybe the functions ord() and chr().


i do see the problem with my method in that theres allways going to be something misencrypted but i dont really know what u mean by touching each letter only once and using chr and ord. chr and ord turn things into and outof ascii yes?. are you suggesting go through the list letter by letter and changing it to ascii then adding 1? then changing it back to a number using ord? what would happen then at z then when it would change it to [ maybe a if statement to see if it ascii code was that then insted of adding one chaning it to 97 for a?. ill see what i can do .
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,414
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 9
Solved Threads: 173
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Very basic de/encrypt program

  #9  
Dec 3rd, 2006
If you just want to do rotational crypting, Python has that builtin ...
  1. # example of simple encoding using rot13 encoding
  2. # alphabet is shifted by 13 positions to nopqrstuvwxyzabcdefghijklm
  3. # so original 'a' becomes 'n' and so on
  4.  
  5. text = "i am crazy"
  6.  
  7. print "original =", text # i am crazy
  8.  
  9. encoded = text.encode('rot13')
  10.  
  11. print "encoded =", encoded # v nz penml
  12.  
  13. decoded = encoded.encode('rot13')
  14.  
  15. print "decoded =", decoded # i am crazy
May 'the Google' be with you!
Reply With Quote  
Join Date: Jul 2006
Posts: 562
Reputation: jrcagle is on a distinguished road 
Rep Power: 4
Solved Threads: 72
jrcagle jrcagle is offline Offline
Posting Pro

Re: Very basic de/encrypt program

  #10  
Dec 4th, 2006
Originally Posted by Haze View Post
are you suggesting go through the list letter by letter and changing it to ascii then adding 1? then changing it back to a number using ord? what would happen then at z then when it would change it to [ maybe a if statement to see if it ascii code was that then insted of adding one chaning it to 97 for a?. ill see what i can do .


Precisely. It's much cleaner and faster than the text.replace() calls.

Jeff
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

DaniWeb Python Marketplace
Thread Tools Display Modes

Other Threads in the Python Forum

All times are GMT -4. The time now is 6:18 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC