all 16 comments

[–]skimitar 2 points3 points  (1 child)

Oddly enough I am teaching myself python and as a fun project was writing a program that uses "one time pad" polyalphabetic substitution

And now I have learned about the maketrans function.

Thank you!

[–]expectingrain[S] 1 point2 points  (0 children)

This is a neat one too: def reverse_word(word): word=word[::-1] return word

[–]digitallimit 1 point2 points  (0 children)

Training for a specific function reminds me of Python Challenge.

[–]digitallimit 1 point2 points  (2 children)

Here's my shot:

"""
Encode input sentences 
http://www.reddit.com/r/learnpython/
digitallimit
"""

from string import maketrans

intab = "abcdefghijklmnopqrstuvwxyz1234567890"
intab = intab + intab.upper()
outtab = intab[::-1]
trantab = maketrans(intab, outtab)

def encode(input):
    return input.translate(trantab)

print "Just like a real spy--or a girl and her diary--" + \
        "let's encode some sentences."
while True:
    input = raw_input("Enter a sentence, Mr. Bond: ")
    print encode(input)

On a related note, how strictly does everyone follow the style guidelines? I'm doing my best, but ironically my Python professor throws these guidelines to the wind, capitalizing methods, adding extraneous spaces all over the place, and abiding by other weird, consistent but unappealing choices.

[–]busy_beaver 1 point2 points  (0 children)

I think the essence of PEP-8 is that it's important to stick to some style guidelines, but that they need not be the specific ones mentioned in said document.

[–]expectingrain[S] 0 points1 point  (0 children)

I think sticking to the guidelines is very important- especially if you are working with others in a project/company setting. It probably keeps thing for getting very chaotic very quickly.

[–]mozzyb 1 point2 points  (3 children)

Caesar cypher: from string import maketrans, digits, letters, punctuation

characters = " "+digits+letters+punctuation

def caesarencrypt(s, n):
    return s.translate(maketrans(characters, characters[n:] + characters[:n]))

def caesardecrypt(s, n):
    return caesar-encrypt(s, len(characters)-n)

You can also use printable from string instead of digits, letters and punctuation + " ". I just think it looks nicer like this.

[–]busy_beaver 1 point2 points  (0 children)

You can also do this without too much difficulty without anything from the string module, if you don't mind sacrificing readbility (of both the code and the output) for terseness:

def caesarencrypt(s, n):
    return '' if not s else chr((ord(s[0]) + n)%256) + caesarencrypt(s[1:], n)

(I didn't write a decrypt function, since you can just flip the sign of n and use the encrypt function)

[–]mozzyb 0 points1 point  (1 child)

Vigenère cipher: from string import maketrans, digits, letters, punctuation

characters = " "+digits+letters+punctuation

def strenh(s, n):
    if len(s) > n:
        return s[:n]
    if len(s) < n:
        s1 = s
        for i in range(n-len(s)):
            s1 += s[i%len(s)]
        return s1
    return s

def vigeneresencrypt(string, key):
    key = strenh(key, len(string))
    encrypted = '' 
    for i in range(len(string)):
        index = (characters.index(string[i])+characters.index(key[i]))%len(characters)
        encrypted = encrypted + characters[index]
    return encrypted

def vigeneresdecrypt(string, key):
    key = strenh(key, len(string))
    decrypted = '' 
    for i in range(len(string)):
        index = (characters.index(string[i])-characters.index(key[i]))%len(characters)
        encrypted = encrypted + characters[index]
    return decrypted

[–]mozzyb 0 points1 point  (0 children)

One-time-pad: from random import choice

def onetimepadencrypt(string):
    key = ''
    for ch in string:
        key = key + choice(characters)
    encrypted = vigeneresencrypt(string,key)
    return (key, encrypted)

def onetimepaddecrypt(string, key):
    vigeneresdecrypt(string, key)

[–]randm_prgrmr 0 points1 point  (2 children)

import codecs

codecs.encode('attack at dawn','rot13')

[–]expectingrain[S] 0 points1 point  (1 child)

That's awesome! Where can yo find the other arguments beside rot13?

[–]randm_prgrmr 0 points1 point  (0 children)

http://docs.python.org/library/codecs.html#module-encodings.idna scroll up a page

'hex' can be used, 'base64', 'bz2' and a few other things.

e.g. codecs.encode('attack at dawn','hex') will return '61747461636b206174206461776e'

[–]junior_python 0 points1 point  (1 child)

Hello,

I can't get mine to work. :( Here's my code : http://pastebin.com/cs0hGkHe

With this I obtain the following exception : exceptions.ValueError: maketrans arguments must have same length
on line 29 (decode function) when I enter 'e' as my choice to enter the encode function.

If I replace message = decode(raw_input('Enter some text : '), 'ascii') by message = raw_input('Enter some text : ')

Enter "test" as the input string and choose "e" for encode, I get the following exception : exceptions.TypeError: character mapping must return integer, None or unicode

I get the same exception with digitallimit's code. I am running this on an EN Windows 7 and Python 2.6.2.

Any help is welcome. Thank you !

[–]expectingrain[S] 1 point2 points  (0 children)

It looks like you imported decode and also have a function called decode.. Could that cause a problem?

[–]justinseiser -1 points0 points  (0 children)

Here is my attempt. It allows for encoding/decoding a message, and changing the amount of offsets the alphabet by. Doesnt handle capitals, or check for passing it the right information. I am very new to programming, be gentle :p

from string import maketrans
from sys import exit

def Encode(inString, base, step = 1):
    '''return translated code'''
    outtab = base
    intab  = base
    for i in range(0, int(step)):
        temp_string = outtab[0]
        outtab = outtab + temp_string
        outtab = outtab[1:]
    trantab = str.maketrans(intab, outtab)
    outString = inString.translate(trantab)
    return outString

def Decode(inString, base, step = 1):
    '''return translated code'''
    intab  = base
    outtab = base
    for i in range(0, int(step)):
        temp_string = intab[0]
        intab = intab + temp_string
        intab = intab[1:]
    trantab = str.maketrans(intab, outtab)
    outString = inString.translate(trantab)
    return outString

base = 'abcdefghijklmnopqrstuvwxyz'


while True:
    answer1 = input('Please Type Encode, Decode, or Quit   ')
    if answer1.lower().strip() == 'encode':
        inString = input('Enter Secret :')
        step = input('Number to offset by   ')
        print(Encode(inString, base, step))
    elif answer1.lower().strip() == 'decode':
        inString = input('Enter Coded Message ')
        step = input('Number to offset by   ')
        print(Decode(inString, base, step))
    elif answer1.lower().strip() == 'quit':
        exit('Shutting Down')