user7795699
user7795699

Reputation:

Caesar cipher brute force into one function

def caesar_decrypt(s,n):
    s1=""
    m = n % 26 if n > 26 else n
    for c in s:
        if c.isalpha():
          x = ord(c) - m
          if c.islower():
             c = chr(x + 26) if x < ord('a') else chr(x)
          elif c.isupper():
             c = chr(x + 26) if x < ord('A') else chr(x)
        s1 += c
    return s1

def brute_force_decrypt(ciphertext):
    for i in range(1,27):
        d=caesar_decrypt(ciphertext,i)
        print (i,d)
brute_force_decrypt(open('text.txt').read())

So, my code does a fine job, but I want the code to be put into one function called brute_force_decrypt(ciphertext). I'm not sure on how to combine the two function I have. I need some help.

Upvotes: 1

Views: 415

Answers (2)

nikpod
nikpod

Reputation: 1278

You can include the code of caesar_decrypt(s,n) in brute_force_decrypt(ciphertext)

def brute_force_decrypt(ciphertext):
    for n in range(1,27):
        s1=""
        m = n % 26 if n > 26 else n
        for c in ciphertext:
            if c.isalpha():
              x = ord(c) - m
              if c.islower():
                 c = chr(x + 26) if x < ord('a') else chr(x)
              elif c.isupper():
                 c = chr(x + 26) if x < ord('A') else chr(x)
            s1 += c
        d = s1
        print (n,d)
brute_force_decrypt(open('text.txt').read())

(Note the change in variable i to n)

Upvotes: 1

zaph
zaph

Reputation: 112855

Don't, a function is best if it does one thing and is well named.

Instead create another function that calls each of these functions.

The less in a function the easier to understand and the less chance of an error.

Upvotes: 2

Related Questions