Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a Caesar Cipher with multiple shifts

For example, if I were to apply 4 shifts to "breakzone" than it would be intended to be like:

"b" would be shifted by 2 characters "r" would be shifted by 3 characters "e" would be shifted by 4 characters "a" would be shifted by 5 characters and then we'd start back at the initial shift amount at 2: "k" would be shifted by 2 characters etc...

here's what I have so far:

statement = input("Enter string: ")
multiple_shifts = input(int("Enter shift amounts: "))
def caesar(word,multiple_shifts):
    for ch in statement:
        if ch = statement[0]:

I know it's not much but I'm definitely lost and any help is appreciated. Not asking you to "write my own code" just point me in the right direction so I'd greatly appreciate any knowledge of this subject.

like image 653
Chris Avatar asked Nov 26 '25 01:11

Chris


1 Answers

Here's a very crude implementation:

import sys

def caesar(word, shifts):
    word_list = list(word.lower())
    result = []
    s = 0
    for c in word_list:
        next_ord = ord(c) + s + 2
        if next_ord > 122:
            next_ord = 97

        result.append(chr(next_ord))
        s = (s + 1) % shifts
    return "".join(result)

if __name__ == "__main__":
    print(caesar("breakzone", 4))

If you wonder what's with 122 and 97, those are the Unicode values for lower case z and a. You could easily change the above to support full Unicode (e.g. be able to encode H3ll0 for example). Here's a Unicode chart that might help you.

like image 102
Rad'Val Avatar answered Nov 28 '25 04:11

Rad'Val



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!