3
\$\begingroup\$

So this code already works, but I would like to shorten it using list comprehension. Would it be better if it was in 1 line, or many? (I do know that readability is more important than short code, but I would like to master list comprehension, ternary operators, and conditional expressions). Oh yes, if there is ANYTHING I can do to make my code better, more efficient, more readable and shorter, I would LOVE to know!

#Caesar Cipher, only lowercase and spaces    
listString = [x for x in input('What would you like to encode? ')]
change = int(input('How much would you like to shift? '))
change %= 26
def encode(listString,change):
  encoded = []
  for c in listString:
    if ord(c) + change > 122:
      encoded.append(chr(ord(c) + (change - 26)))
      continue
    encoded = [" " if x == chr(32 + change) else x for x in encoded]
    encoded.append(chr(ord(c) + change))
  return "".join(encoded)

print(encode(listString,change))
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

A view more suggestions:

  • Put the function definition at the top
  • [x for x in input()] is the same as just input(). Strings are lists of characters!

Combining my suggestings with the ones by @I0b0 you get something like the following:

def encrypt(char, key):
    '''Encrypt lower and uppercase characters using the caesar cipher.'''
    if char.islower():
        return chr((ord(char) - ord('a') + key) % 26 + ord('a'))
    elif char.isupper():
        return chr((ord(char) - ord('A') + key) % 26 + ord('A'))
    return char

message = input('What would you like to encode? ')
key = int(input('How much would you like to shift? '))
print(''.join([encrypt(c, key) for c in message]))
\$\endgroup\$
2
\$\begingroup\$

Some suggestions:

  • Pull out a function to shift a single character, and your top level code ends up being simply print(''.join([cipher(character) for character in input(…)]))
  • With an array containing the alphabet and a shifted array ("{}{}".format(alphabet[offset:], alphabet[:offset])) you can use str.translate to avoid any ord, chr, punctuation handling etc.
  • Use at least one linter like pycodestyle or flake8 to produce more idiomatic code.
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.