MIT Problem Set 4c: Type Error: Encrypted Message not subscriptable

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># Problem Set 4C
# Name:
# Collaborators:
import json
import ps4b # Importing your work from Part B
### HELPER CODE ###
def load_words(file_name):
'''
file_name (string): the name of the file containing
the list of words to load
Returns: a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
'''
# inFile: file
with open(file_name, 'r') as inFile:
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.extend([word.lower() for word in line.split(' ')])
return wordlist
def is_word(word_list, word):
'''
Determines if word is a valid word, ignoring
capitalization and punctuation
word_list (list): list of words in the dictionary.
word (string): a possible word.
Returns: True if word is in word_list, False otherwise
# Example:
# >>> is_word(word_list, 'bat') returns
# True
# >>> is_word(word_list, 'asdf') returns
# False
# '''
word = word.strip(" !@#$%^&*()-_+={}[]|:;'<>?,./"").lower()
return word in word_list
def get_story_string():
"""
Returns: a story in encrypted text.
"""
f = open("story.txt", "r")
story = str(f.read())
f.close()
return story[:-1]
def get_story_pads():
with open('pads.txt') as json_file:
return json.load(json_file)
WORDLIST_FILENAME = 'words.txt'
### END HELPER CODE ###
def decrypt_message_try_pads(ciphertext, pads):
'''
Given a string ciphertext and a list of possible pads
used to create it find the pad used to create the ciphertext
We will consider the pad used to create it the pad which
when used to decrypt ciphertext results in a plaintext
with the most valid English words. In the event of ties return
the last pad that results in the maximum number of valid English words.
ciphertext (EncryptedMessage): The ciphertext
pads (list of lists of ints): A list of pads which might have been used
to encrypt the ciphertext
Returns: (PlaintextMessage) A message with the decrypted ciphertext and the best pad
'''
word_list = load_words('words.txt')
max_word_count = 0
best_pad = None
best_decrypted_message = ""
for pad in pads:
# Debug: show current pad being tried
print(f"Trying pad: {pad}")
# Decrypt the message using the current pad
encrypted_message = ps4b.EncryptedMessage(ciphertext)
decrypted_message_object = encrypted_message.decrypt_message(pad)
print(type(decrypted_message_object))
decrypted_message = decrypted_message_object.get_text()
# Split the decrypted message into words
decrypted_message_list = decrypted_message.split()
# Count the number of valid English words
word_count = sum(is_word(word_list, word) for word in decrypted_message_list)
# Debug: Show the decrypted message and word count
# Update best pad and message if this pad produces more valid words
if word_count > max_word_count:
max_word_count = word_count
best_pad = pad
best_decrypted_message = decrypted_message
elif word_count == max_word_count:
best_pad = pad
best_decrypted_message = decrypted_message
# Debug: Final selection
return ps4b.PlaintextMessage(best_decrypted_message, best_pad)
def decode_story():
'''
Write your code here to decode Bob's story using a list of possible pads
Hint: use the helper functions get_story_string and get_story_pads and your EncryptedMessage class.
Returns: (string) the decoded story
'''
raise NotImplementedError # delete this line and replace with your code here
if __name__ == '__main__':
# # Uncomment these lines to try running decode_story()
# story = decode_story()
# print("Decoded story: ", story)
pass
</code>
<code># Problem Set 4C # Name: # Collaborators: import json import ps4b # Importing your work from Part B ### HELPER CODE ### def load_words(file_name): ''' file_name (string): the name of the file containing the list of words to load Returns: a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. ''' # inFile: file with open(file_name, 'r') as inFile: # wordlist: list of strings wordlist = [] for line in inFile: wordlist.extend([word.lower() for word in line.split(' ')]) return wordlist def is_word(word_list, word): ''' Determines if word is a valid word, ignoring capitalization and punctuation word_list (list): list of words in the dictionary. word (string): a possible word. Returns: True if word is in word_list, False otherwise # Example: # >>> is_word(word_list, 'bat') returns # True # >>> is_word(word_list, 'asdf') returns # False # ''' word = word.strip(" !@#$%^&*()-_+={}[]|:;'<>?,./"").lower() return word in word_list def get_story_string(): """ Returns: a story in encrypted text. """ f = open("story.txt", "r") story = str(f.read()) f.close() return story[:-1] def get_story_pads(): with open('pads.txt') as json_file: return json.load(json_file) WORDLIST_FILENAME = 'words.txt' ### END HELPER CODE ### def decrypt_message_try_pads(ciphertext, pads): ''' Given a string ciphertext and a list of possible pads used to create it find the pad used to create the ciphertext We will consider the pad used to create it the pad which when used to decrypt ciphertext results in a plaintext with the most valid English words. In the event of ties return the last pad that results in the maximum number of valid English words. ciphertext (EncryptedMessage): The ciphertext pads (list of lists of ints): A list of pads which might have been used to encrypt the ciphertext Returns: (PlaintextMessage) A message with the decrypted ciphertext and the best pad ''' word_list = load_words('words.txt') max_word_count = 0 best_pad = None best_decrypted_message = "" for pad in pads: # Debug: show current pad being tried print(f"Trying pad: {pad}") # Decrypt the message using the current pad encrypted_message = ps4b.EncryptedMessage(ciphertext) decrypted_message_object = encrypted_message.decrypt_message(pad) print(type(decrypted_message_object)) decrypted_message = decrypted_message_object.get_text() # Split the decrypted message into words decrypted_message_list = decrypted_message.split() # Count the number of valid English words word_count = sum(is_word(word_list, word) for word in decrypted_message_list) # Debug: Show the decrypted message and word count # Update best pad and message if this pad produces more valid words if word_count > max_word_count: max_word_count = word_count best_pad = pad best_decrypted_message = decrypted_message elif word_count == max_word_count: best_pad = pad best_decrypted_message = decrypted_message # Debug: Final selection return ps4b.PlaintextMessage(best_decrypted_message, best_pad) def decode_story(): ''' Write your code here to decode Bob's story using a list of possible pads Hint: use the helper functions get_story_string and get_story_pads and your EncryptedMessage class. Returns: (string) the decoded story ''' raise NotImplementedError # delete this line and replace with your code here if __name__ == '__main__': # # Uncomment these lines to try running decode_story() # story = decode_story() # print("Decoded story: ", story) pass </code>
# Problem Set 4C
# Name:
# Collaborators:

import json
import ps4b # Importing your work from Part B

### HELPER CODE ###
def load_words(file_name):
    '''
    file_name (string): the name of the file containing
    the list of words to load

    Returns: a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    '''
    # inFile: file
    with open(file_name, 'r') as inFile:
        # wordlist: list of strings
        wordlist = []
        for line in inFile:
            wordlist.extend([word.lower() for word in line.split(' ')])
        return wordlist


def is_word(word_list, word):
    '''
    Determines if word is a valid word, ignoring
    capitalization and punctuation

    word_list (list): list of words in the dictionary.
    word (string): a possible word.

    Returns: True if word is in word_list, False otherwise

    # Example:
    # >>> is_word(word_list, 'bat') returns
    # True
    # >>> is_word(word_list, 'asdf') returns
    # False
    # '''
    word = word.strip(" !@#$%^&*()-_+={}[]|:;'<>?,./"").lower()
    return word in word_list


def get_story_string():
    """
    Returns: a story in encrypted text.
    """
    f = open("story.txt", "r")
    story = str(f.read())
    f.close()
    return story[:-1]


def get_story_pads():
    with open('pads.txt') as json_file:
        return json.load(json_file)


WORDLIST_FILENAME = 'words.txt'
### END HELPER CODE ###


def decrypt_message_try_pads(ciphertext, pads):
    '''
    Given a string ciphertext and a list of possible pads
    used to create it find the pad used to create the ciphertext

    We will consider the pad used to create it the pad which
    when used to decrypt ciphertext results in a plaintext
    with the most valid English words. In the event of ties return
    the last pad that results in the maximum number of valid English words.

    ciphertext (EncryptedMessage): The ciphertext
    pads (list of lists of ints): A list of pads which might have been used
        to encrypt the ciphertext

    Returns: (PlaintextMessage) A message with the decrypted ciphertext and the best pad
    '''
    word_list = load_words('words.txt')

    max_word_count = 0
    best_pad = None
    best_decrypted_message = ""

    for pad in pads:
        # Debug: show current pad being tried
        print(f"Trying pad: {pad}")

        # Decrypt the message using the current pad
        encrypted_message = ps4b.EncryptedMessage(ciphertext)
        decrypted_message_object = encrypted_message.decrypt_message(pad)
        print(type(decrypted_message_object))
        decrypted_message = decrypted_message_object.get_text()

        # Split the decrypted message into words
        decrypted_message_list = decrypted_message.split()

        # Count the number of valid English words
        word_count = sum(is_word(word_list, word) for word in decrypted_message_list)

        # Debug: Show the decrypted message and word count


        # Update best pad and message if this pad produces more valid words
        if word_count > max_word_count:
            max_word_count = word_count
            best_pad = pad
            best_decrypted_message = decrypted_message
        elif word_count == max_word_count:
            best_pad = pad
            best_decrypted_message = decrypted_message

    # Debug: Final selection

    return ps4b.PlaintextMessage(best_decrypted_message, best_pad)







def decode_story():
    '''
    Write your code here to decode Bob's story using a list of possible pads
    Hint: use the helper functions get_story_string and get_story_pads and your EncryptedMessage class.

    Returns: (string) the decoded story

    '''
    raise NotImplementedError  # delete this line and replace with your code here



if __name__ == '__main__':
    # # Uncomment these lines to try running decode_story()
    # story = decode_story()
    # print("Decoded story: ", story)
    pass

Hi guys, I am currently working on MIT Pset 4, and I pass all the test running, but failed with one test which is test_try_pads. The error message is “TypeError: ‘EncryptedMessage’ object is not subscriptable’. I wonder how to solve this error, after searching a lot of chatgpt stuffs and google. Thanks a bunch if you guys can help me.

New contributor

Michael Jordan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật