#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    16
    Rep Power
    0

    Could anyone help me on a Python programming assignment?


    Here is the assignment:

    Your program needs to decode an encrypted text file called "encrypted.txt". The person who wrote it used a cipher specified in "key.txt". This key file would look similar to the following:

    A B
    B C
    C D
    D E
    E F
    F G
    G H
    H I
    I J
    J K
    K L
    L M
    M N
    N O
    O P
    P Q
    Q R
    R S
    S T
    T U
    U V
    V W
    W X
    X Y
    Y Z
    Z A

    The left column represents the plaintext letter, and the right column represents the corresponding ciphertext.

    Your program should decode the "encrypted.txt" file using "key.txt" and write the plaintext to "decrypted.txt".



    This is what I have so far:

    Code:
    def decoder(filename):
        infile = open(filename, "r")
        cypher = dict()
        count = 0
        for line in infile:
            parts = line.split() 
            count += 1
            plain = parts[0]
            code_b = parts[1]
            cypher[plain] = code_b
        infile.close()
        return cypher
        
    def replace_all(filename):
        infile = open(filename, "r")
        for i in infile:
            decyrpted = infile.replace(plain, code_b)
        infile.close()
        return decrypted
        
    code_break = decoder("key.txt")
    new_code = replace_all("encrypted.txt")
    outfile = open("decrypted.txt", "w")
    for line in outfile:
        outfile.write(line + "\n" )
    outfile.close()
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,995
    Rep Power
    481
    Your replace_all function needs the cypher dictionary. Pass it as a function argument, and use it correctly.


    Or, if you're really stuck, I provide the following skeleton. You'd just need to write the guts of
    decrypt_character(c,cypher)
    and repair any other bugs I introduced. The skeleton configures the algorithm into steps which I think many experienced programmers would agree is a more logical/useful grouping of tasks.


    Code:
    #Your program should decode the "encrypted.txt" file using "key.txt" and write the plaintext to "decrypted.txt".
    
    # count doesn't do anything, removed.
    # looks like your decoder function worked.
    def decoder(filename):
        cypher = dict()
        with open(filename, "r") as infile:   # use the with context statement.  Automatically closes the file.
            for line in infile:
                parts = line.split()
                plain = parts[0]
                code_b = parts[1]
                cypher[plain] = code_b
        return cypher
    
    
    
    
    def decrypt_character(c,cypher):
        # your code needs to handle characters that are not in the cypher dictionary
        # as well as those that are in the cypher dictionary.
        return the_decrypted_character
    
    
    
    
    def replace_all(text,cypher):
        t = list(text)
        for (i,c) in enumerate(t):
            t[i] = decrypt_character(c,cypher)
        return ''.join(t)
    
    code_break = decoder("key.txt")
    
    with open('encrypted.txt','r') as infile:
        et = infile.read()                    # et is the entire encrypted text
    
    dc = replace_all(et,code_break)           # replace all needs the cypher dictionary!
    
    with open('decrypted.txt','w') as outfile:
        outfile.write(dc)
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    16
    Rep Power
    0
    Ok, this is what I have so far: It runs but it doesn't decode it, it just repeats what the coded message was over and over.

    Code:
    class Decode(object):
        def decoder(filename):
            cypher = dict()
            infile = open(filename, "r")
            for line in infile:
                parts = line.split()
                plain = parts[0]
                code_b = parts[1]
                cypher[plain] = code_b
            infile.close()
            return cypher
            
        def replace_all(filename, cypher):
            infile = open(filename, "r")
            decrypted = ""
            for i in infile:
                for plain in cypher:
                    decrypted += i.replace(plain, cypher[plain])
            infile.close()
            return decrypted
        
        code_break = decoder("key.txt")
        outfile = open("decrypted.txt", "w")
        new_code = replace_all("encrypted.txt", code_break)
        outfile.write(new_code + "\n" )
        outfile.close()
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,995
    Rep Power
    481
    you have written the class method
    Code:
    class Decode(object):
        def decoder(filename):
    Learn soon that python implicitly passes the object to a class method as the first argument. Where you gave "filename" would actually be the object instance.

    Study this example. The way to explain the message as truth is that, as I've said, python implicitly passed an object (of type c) into the method. That's the 1 given.
    Code:
    >>> class c:
    ...  def f():
    ...   pass
    ... 
    >>> c().f()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: f() takes no arguments (1 given)
    >>>

    If this were an interview question, I'd be pleased to submit this answer (probably why I'm unemployed?)

    Code:
    #! python3
    
    '''
      Your program needs to decode an encrypted text file called
      "encrypted.txt". The person who wrote it used a cipher specified in
      "key.txt". This key file would look similar to the following:
    
      The left column represents the plaintext letter, and the right
      column represents the corresponding ciphertext.
    
      Your program should decode the "encrypted.txt" file using "key.txt"
      and write the plaintext to "decrypted.txt".
    '''
    
    import sys
    
    class TomMixError(ValueError):
        pass
    
    class TomMixCodeRing(object):
    
        '''
            TomMixCodeRing(file_object)
            file_object has three characters per line,
            the plain text character, a space character, and the cipher character.
    
            The constructor loads the secret code.
    
            >>> import sys
            >>> if sys.version[0] < '3':
            ...     raise TomMixError('This docstring test requires python2')
            >>> import io
            >>> code = TomMixCodeRing(io.StringIO('a e'))
            >>> code.encode('bat')
            'bet'
            >>> code.encode('beat')
            'beet'
            >>> code.decode('beet')             # non-cyclic ciphers fail.
            'baat'
        '''
    
        def __init__(self,keyfile):
            '''
                build the translation dictionaries, and save them in this object
            '''
            encode = {}
            decode = {}
            try:
                for line in keyfile:
                    (plain,cipher) = line.split()
                    encode[plain] = cipher
                    decode[cipher] = plain
            except:
                raise TomMixError(self.__class__.__doc__)
            self.en = encode
            self.de = decode
    
        def decode(self,encryption):
            return self.replace_all(encryption,self.de)
    
        def encode(self,plaintext):
            return self.replace_all(plaintext,self.en)
    
        @staticmethod      # the object is NOT passed as first argument
        def replace_all(s,d):
            '''
                using replace_all avoids duplicate code
            '''
            L = []
            append = L.append
            for c in s:
                if c in d: # I meant this by "handle characters not given by your code
                    c = d[c]
                append(c)
            return ''.join(L)
    OK, please this post repeatedly throughout your python programming career. It's too long and I've said a lot.
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    2
    Rep Power
    0
    Hi friends..
    I am Ajim..
    Friends i was also trapped in the same situation once. someone suggested me to take help online through the search engines. Then i found some helpful sites like acropolismentors ./ they are really good.. i usually take help from the search engines.

IMN logo majestic logo threadwatch logo seochat tools logo