Click here to Skip to main content
15,885,914 members
Home / Discussions / Python
   

Python

 
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
AnswerRe: [Help]H.W issues Pin
Richard MacCutchan15-Oct-22 9:05
mveRichard MacCutchan15-Oct-22 9:05 
QuestionError - 'module' object has no attribute 'askopenfilename' Pin
s yu13-Oct-22 2:59
s yu13-Oct-22 2:59 
AnswerRe: Error - 'module' object has no attribute 'askopenfilename' Pin
Richard MacCutchan13-Oct-22 3:12
mveRichard MacCutchan13-Oct-22 3:12 
QuestionUnexpected token 'root' Pin
s yu12-Oct-22 5:45
s yu12-Oct-22 5:45 
AnswerRe: Unexpected token 'root' Pin
Richard MacCutchan12-Oct-22 6:39
mveRichard MacCutchan12-Oct-22 6:39 
GeneralRe: Unexpected token 'root' Pin
s yu12-Oct-22 7:28
s yu12-Oct-22 7:28 
GeneralRe: Unexpected token 'root' Pin
Richard MacCutchan12-Oct-22 7:57
mveRichard MacCutchan12-Oct-22 7:57 
GeneralRe: Unexpected token 'root' Pin
Dave Kreskowiak12-Oct-22 12:08
mveDave Kreskowiak12-Oct-22 12:08 
GeneralRe: Unexpected token 'root' Pin
s yu13-Oct-22 2:28
s yu13-Oct-22 2:28 
Questionhello, good day, does anyone know how to solve this problem? It would help me a lot if you could explain how to do it Pin
Member 157924299-Oct-22 18:35
Member 157924299-Oct-22 18:35 
AnswerRe: hello, good day, does anyone know how to solve this problem? It would help me a lot if you could explain how to do it Pin
Richard MacCutchan9-Oct-22 22:16
mveRichard MacCutchan9-Oct-22 22:16 
AnswerRe: hello, good day, does anyone know how to solve this problem? It would help me a lot if you could explain how to do it Pin
Reverend Jim10-Jun-23 4:51
Reverend Jim10-Jun-23 4:51 
QuestionCan you have a virtual environment based on a virtual environment? Pin
Chris Maunder5-Oct-22 12:16
cofounderChris Maunder5-Oct-22 12:16 
AnswerRe: Can you have a virtual environment based on a virtual environment? Pin
trønderen5-Oct-22 12:34
trønderen5-Oct-22 12:34 
AnswerRe: Can you have a virtual environment based on a virtual environment? Pin
Richard MacCutchan5-Oct-22 22:54
mveRichard MacCutchan5-Oct-22 22:54 
GeneralRe: Can you have a virtual environment based on a virtual environment? Pin
Chris Maunder18-Oct-22 3:16
cofounderChris Maunder18-Oct-22 3:16 
GeneralRe: Can you have a virtual environment based on a virtual environment? Pin
Richard MacCutchan18-Oct-22 3:45
mveRichard MacCutchan18-Oct-22 3:45 

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.