Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old November 8th, 2012, 10:23 PM
blobman23 blobman23 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 16 blobman23 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 41 m 15 sec
Reputation 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()

Reply With Quote
  #2  
Old November 9th, 2012, 09:54 AM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,383 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 13 h 44 m 29 sec
Reputation Power: 383
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!

Reply With Quote
  #3  
Old November 18th, 2012, 02:35 PM
blobman23 blobman23 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 16 blobman23 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 41 m 15 sec
Reputation 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()

Reply With Quote
  #4  
Old November 18th, 2012, 04:06 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,383 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 13 h 44 m 29 sec
Reputation Power: 383
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.

Reply With Quote
  #5  
Old December 25th, 2012, 10:23 PM
ajim ajim is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 2 ajim User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 7 m 17 sec
Reputation 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.

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Could anyone help me on a Python programming assignment?

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap