Click here to Skip to main content
15,909,896 members
Home / Discussions / Python
   

Python

 
AnswerRe: How to iterate within a list in python? Pin
Richard MacCutchan24-Nov-22 22:13
mveRichard MacCutchan24-Nov-22 22:13 
AnswerRe: How to iterate within a list in python? Pin
Gulshan Negi15-Mar-23 23:28
professionalGulshan Negi15-Mar-23 23:28 
QuestionPlz Help Trying to make driving game more realistic and fun (pygame) Pin
s897422-Nov-22 20:41
s897422-Nov-22 20:41 
AnswerRe: Plz Help Trying to make driving game more realistic and fun (pygame) Pin
Gulshan Negi14-Feb-23 21:34
professionalGulshan Negi14-Feb-23 21:34 
QuestionPython Code Related Pin
Mr.Zeenore18-Nov-22 12:28
Mr.Zeenore18-Nov-22 12:28 
AnswerRe: Python Code Related Pin
Dave Kreskowiak18-Nov-22 17:55
mveDave Kreskowiak18-Nov-22 17:55 
GeneralRe: Python Project Question Pin
Mr.Zeenore18-Nov-22 21:36
Mr.Zeenore18-Nov-22 21:36 
AnswerRe: Python Project Question Pin
OriginalGriff18-Nov-22 21:36
mveOriginalGriff18-Nov-22 21:36 
GeneralRe: Python Project Question Pin
Craig Robbins7-Dec-22 1:06
Craig Robbins7-Dec-22 1:06 
GeneralRe: Python Project Question Pin
trønderen7-Dec-22 3:04
trønderen7-Dec-22 3:04 
GeneralRe: Python Code Related Pin
Mr.Zeenore18-Nov-22 20:09
Mr.Zeenore18-Nov-22 20:09 
GeneralRe: Python Code Related Pin
Dave Kreskowiak19-Nov-22 4:07
mveDave Kreskowiak19-Nov-22 4:07 
AnswerRe: Python Code Related Pin
Richard MacCutchan18-Nov-22 22:35
mveRichard MacCutchan18-Nov-22 22:35 
QuestionPython vs. PHP - Web Application Development Pin
vitaassure15-Nov-22 10:30
professionalvitaassure15-Nov-22 10:30 
AnswerRe: Python vs. PHP - Web Application Development Pin
Gerry Schmitz15-Nov-22 12:11
mveGerry Schmitz15-Nov-22 12:11 
AnswerRe: Python vs. PHP - Web Application Development Pin
Richard MacCutchan15-Nov-22 21:34
mveRichard MacCutchan15-Nov-22 21:34 
QuestionPython code Pin
Masande Nogemane3-Nov-22 6:34
Masande Nogemane3-Nov-22 6:34 
AnswerRe: Python code Pin
Richard MacCutchan3-Nov-22 7:47
mveRichard MacCutchan3-Nov-22 7:47 
QuestionPython Code Heuristic Algorithm Pin
Member 1581467330-Oct-22 19:31
Member 1581467330-Oct-22 19:31 
AnswerRe: Python Code Heuristic Algorithm Pin
OriginalGriff30-Oct-22 19:34
mveOriginalGriff30-Oct-22 19:34 
QuestionHow to secure Python application using license key? Pin
Alex Dunlop26-Oct-22 5:39
Alex Dunlop26-Oct-22 5:39 
AnswerRe: How to secure Python application using license key? Pin
Gerry Schmitz15-Nov-22 12:04
mveGerry Schmitz15-Nov-22 12:04 
QuestionHow to set activation system to ready python project? Pin
MR-XAN77715-Oct-22 22:38
MR-XAN77715-Oct-22 22:38 
AnswerRe: How to set activation system to ready python project? Pin
Richard MacCutchan16-Oct-22 0:48
mveRichard MacCutchan16-Oct-22 0:48 
Question[Help]H.W issues Pin
אנטון מוטרוק 202115-Oct-22 7:10
אנטון מוטרוק 202115-Oct-22 7:10 
Python
import re


# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Part 1
# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
def creation_of_dictionary(message):
    print(f"In creation_of_dictionary: message= {message}")
    m = {}
    l = []
    z4 = {}
    mc = ['r', 'o', 't', 'e']
    for i in message:
        if i.isalpha():
            b = i.lower()
            l.append(b)
    print(f"creation_of_dictionary:l={l}")

    for g in range(len(l)):
        f = l.count(l[g])
        m[l[g]] = f
        tuples = m.items()
        tuples = sorted(tuples, key=lambda tuples: tuples[1])
    print(f"tuples = {tuples}")

    for e in [-4, -3, -2, -1]:
        z4[mc[m]] = tuples[e][0]
        z4[tuples[e][0]] = mc[e]

    print(z4)
    return (z4)


# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Part 2
# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
def decode(message, dict):
    lists = []
    for m in message:
        l = m.lower()
        lists.append(l)
    for s in range(len(lists)):
        if lists[s] in dict.keys():
            lists[s] = dict[lists[s]]
    b = ''.join(lists)
    return b


# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Part 3
# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
def txt_decode(path):
    lines = []
    newdic = {}
    m = open(path, 'r')
    q = m.readlines()
    m.close()
    for i in range(len(q)):
        q[i] = q[i].rstrip()
    newdic = creation_of_dictionary(''.join(q))
    for t in range(len(q)):
        lines.append(decode(q[t], newdic))
    f = open(path, 'a')
    f2 = open("result.txt", 'w')
    f.write("\n The encryption for the above text is:\n")
    for n in range(len(lines)):
        f.write(lines[n])
        f2.write(lines[n])
        f.write('\n')
        f2.write('\n')
        f.close()


# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Part 4
# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
def long_word(message_file):
    register = re.compile('[^a-zA-Z]')
    with open(message_file, 'r') as infile:
        messages = infile.read().split()

    max_option = len(max(messages, key=len))
    word = [word for word in messages if len(word) == max_option]
    final_word = []
    for z in range(0, len(word)):
        word[z] = register.sub('', word[z])
        if len(word[z]) == max_option:
            final_word.append(word[z])
    return final_word


def file_length(f_mean):
    with open(f_mean) as f:
        for o, p in enumerate(f):
            pass
    return o + 1


# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Conclusion
# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
def main():
    txt_decode("message.txt")
    f = open("message.txt", 'a')
    long = long_word("result.txt")
    num_of_try = file_length("result.txt")
    for m in range(0, num_of_try):
        f.write(long[0] + "")
    f.write("\n")
    f.close()


# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

if __name__ == '__main__':
    main()

Part 1
replace 4 most common letters in the text with 4 most common letters in the English language ‘e’,’t’,’o’,’r’.
in example: 'a' is most common - replace it with 'e', and 'e' with 'a'
in example: abcd most common chars in text:  a <-> e, b <-> t, c <-> o, d <-> r

Create a function replace_common_occurences(str) -> replaced_dict - that will include the most common letters and their replacements.
The function needs to find the most common chars (count occurences)
The function will receive a text as a string and will return the relevant dictionary - replaced_dict
{'a': 'e', 'c': 'o', 'b': 't', 'e': 'a', 'd': 'r', 'o': 'c', 'r': 'd', 't': 'b'}

1. The dictionary will include only letters that were changed.
2. include only letters - not numbers, spaces, etc.
3. code must be case insensitive - dictionary only lower case
4. check:
    a. There are at least four different letters in your text
    b. for for every popular letter - there is no letter that appears the same number of times.
    c. the most popular letters are not 'e', 't', 'o', 'r'
"""

"""
Part 2
1. Write a function replace_chars_in_text(text to change, replaced_dict) -> changed str
2. The function will iterate over the str and for each char
   if there is a replaced_dict[key] - replace with the value, otherwise do not change.
3. Example: str             = ///bha Taa3add, bha Tdaer, enr b7ha Fdcccccbbb
            replaced_dict   =  {'a': 'e', 'c': 'o', 'b': 't', 'e': 'a', 'd': 'r', 'o': 'c', 'r': 'd', 't': 'b'} 
            replaced_str    =  ///the bee3err, the bread, and t7he frooooottt
"""

"""
Part 3
Create a function: decode_text(path to encrypted text file) to update the message text file
call:
    1. replace_common_occurences(str) -> replaced_dict
    2. replace_chars_in_text(text to change, replaced_dict) -> changed str
add to message.txt file: 'the encryption for the above text is:' ....decrypted text....
create another text file - results.txt - include only the decrypted results. 
notes: common chars should be done over all text file, not line by line. 
ignore \n.
"""

"""
Part 4
Create a function find_longest_word(path to results.txt) -> list of longest words. 
return the longest word in result.txt file (decrypted text) - count only alphabetical chars.
Removing all non alpha chars - import re, regex=re.compile("[^a-zA-Z]") list[i]=regex.sub(", your string)
Create a function count_num_of_lines(path to results.txt) -> num of lines.

main()
1. decrypt message - part 1,2,3
2. write to the original message (append) the first value of the longest words list return from  find_longest_word(path to results.txt) 
   times the number of lines in results.txt file. 
   Example:  Your longest word is "BOOBOBA", The number of lines is 2.
   Add to original message.txt - BOOBOBA BOOBOBA
"""


'Puackich, hvhnkrally oaths phufhck. All ymr nhhd is Pykemn.'
J.U.U.U Kmltin.
mmps iks nmk eio; ---> hkmu



"""

hi guys pls advise i added the code i managed to write and the H.W description below basically the code supposed to receive and than decode string message but i am getting errors such as message.txt file doesnt exist etc

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.