5
\$\begingroup\$

This is a program that can decrypt the codes that have been encrypted using the algorithm that my previously posted encryption program follows, you just need to enter the encrypted text from that program.

I got a lot of suggestions from people on the encryption post, I have tried to make this program as short as possible (in my efforts), I did not use the method they suggested to shorten functions because I don't want to use it without understanding how it works, I will implement it in my further programs as soon as I understand it...

Thank You for the suggestions on the previous program, it helped me reduce the length of this program by 16 lines.

Please let me know what you think about this program

Python Code :

alphabets = 'abcdefghijklmnopqrstuvwxyz'

def position_in_alphabets(tofind):
    for i in range(0,26):
        if tofind == alphabets[i]:
            position = i+1
            break
    return position

def decrypt(a):
    output = ''
    for i in range(0,len(a)):
        character = a[i]
        z = i+1
        y = position_in_alphabets(character)
        x = z+y-26
        if x>len(alphabets):
            x = x % len(alphabets)
        alpha = alphabets[x-1]
        output += alpha
    return output

print ()
print ("NOTE : Please enter just lowercase characters (no special characters) and no spaces")
print ()
given = input("Please enter the word to be decrypted : ")
output = decrypt(given)
print ()
print ("The word which is coded as ",given," is : ",output)

Thank You :)

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

Use built in methods!

Your position_in_alphabets function can be reduced to one line. In fact, replace y = ... with the following:

alphabets.index(character) + 1

index returns the first occurrence of the character in question. Since you're working with the alphabet, it will return the position of the character in that string. Then you just need to add one.

Never trust user input

Instead of trusting the user will only enter lowercase characters after telling them to do so, call .lower() on the input to change the string to all lowercase letters.


I'm going to step through each line of the main function now.


f"" strings

I would use f"" strings so you can directly format your variables in your strings. In this case, it reduces the clutter that print("...", var, "...", var, "...") causes. It would instead be print(f"... {var} ... {var} ...").

Naming conventions (PEP 8)

a isn't really a good parameter name. A variable/parameter name should represent what that variable is holding or is doing. I would use string, since you're working with them in this program.

def decrypt(string):

Use enumerate

enumerate allows you to work through an iterable with the index and the value at that position in the iterable. It gets rid of having to iterable[i] and all that junk.

output = ''
spaces = 0
for index, character in enumerate(string):

Allowing spaces

Spaces are really easy to deal with. If the character is a space, simply add " " to the output and continue, quite literally, to the next iteration.

if character == " ":
    output += " "
    spaces += 1
    continue

Compress your computations

Instead of having a bunch of one character variable names x, y, z, I would do all the computations in one step and assign them to a variable. I've done so, and used position, because that's what you're calculating.

position = (index + 1) + (alphabet.index(character) + 1) - 26

Simplify your reassignments

Have a look at this:

if position > len(alphabet):
    position %= len(alphabet)

It's the same thing as position = position % len(alphabet), but shorter (also called in place modulus). It also works for the other operators (+-*/).

Don't make variables you don't need

The sole purpose of alpha is to hold the value at the passed position in alphabet, then you add alpha to output. How about you just skip the first step and add it right to output?

output += alphabet[position - 1]

All in all, your final program looks like this:

alphabet = 'abcdefghijklmnopqrstuvwxyz'

def decrypt(string: str) -> str:
    output = ''
    spaces = 0
    for index, character in enumerate(string):
        if character == " ":
            output += " "
            spaces += 1
            continue
        position = (index + 1) + (alphabet.index(character) + 1) - len(alphabet)
        if position > len(alphabet):
            position %= len(alphabet)
        output += alphabet[position - 1 - spaces]
    return output

word = input("Please enter the word to be decrypted: ").lower()
output = decrypt(word)
print(f"The word '{word}' decrypted is '{output}'")

We use spaces to shift the index back for every space we've encountered.

\$\endgroup\$
4
  • \$\begingroup\$ Thanks, it was really helpful, but there's one problem, the addition of the space feature interferes with the output, like the output for 'zzzz' is 'abcd', and if the user enters 'zz zz', then shouldn't the output be 'ab cd' instead of 'ab de' as it does in the version that you gave? I want a method in which the value of i does not increase by one when the character is [spcae], so we can count the number of spaces found and then reduce the value of i by the number of spaces...that should work, right? \$\endgroup\$ Commented Mar 27, 2020 at 10:16
  • \$\begingroup\$ I figured it out, we can create a variable number_of_spaces, let's say and every time the character is a space, we can increase the variable by one, and then change the second-last statement of decrypt() to : output+=alphabets[position-1-number_of_spaces], it works, now the output for "zz zz" is "ab cd", Thanks for the review \$\endgroup\$ Commented Mar 27, 2020 at 10:25
  • 1
    \$\begingroup\$ @Rajdeep_Sindhu I missed that, thanks for catching it. The code has been updated. \$\endgroup\$
    – Linny
    Commented Mar 27, 2020 at 10:56
  • \$\begingroup\$ I would have add type annotations @Linny . Great answer tho! \$\endgroup\$
    – Yonlif
    Commented Mar 27, 2020 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.