So I am done with the code below, I will run it like this "python hw3.py < code.txt"
I think I have a problem with the indentation or something. the code.txt has a mixed up text in it that is offset using a caesar cipher but it has to be decoded using letter frequencies... any help would be appreciated

def main():

     from Numeric import *
     from string import maketrans

def translator(text,alphabet,key):
         trantab = maketrans(alphabet,key)
         return text.translate(trantab)

def caesar_decode(ciphertext,s):
         alpha="abcdefghijklmnopqrstuvwxyz"
         return translator(ciphertext,alpha,alpha[-s:]+alpha[:-s])

class frequency_analysis:
    def __init__(self, ciphertext):
        self.cor=[0.64297,0.11746,0.21902,0.33483,1.00000,0.17541,
                  0.15864,0.47977,0.54842,0.01205,0.06078,0.31688,0.18942,
                  0.53133,0.59101,0.15187,0.00748,0.47134,0.49811,0.71296,
                  0.21713,0.07700,0.18580,0.01181,0.15541,0.00583]
self.ciphertext=ciphertext.lower()
self.freq()
self.min_error()
self.key=self.minimum[0]
self.solution=caesar_decode(self.ciphertext,self.minimum[0])

def freq(self):
    self.arr=zeros(26,Float64)
for l in self.ciphertext:
    x=ord(l)
    if (x>=97 and x<=122):
        self.arr[x-97]+=1.0
self.arr/=max(self.arr)

def error(self):
    e=0
for i in range(0,len(self.arr)):
    e += abs(self.arr[i]-self.cor[i])**2
    return e

def min_error(self):
    self.minimum=[0,10000]
for rot in range(0,25):
    e=self.error()
    print rot,e
    if e<self.minimum[1]:
        self.minimum[1]=e
        self.minimum[0]=rot
    x=self.arr[-1]
    del self.cor[-1]
    self.cor.insert(0,x)

ciphertext="ymjwj fwj ybt ydujx tk jshwduynts: tsj ymfy bnqq "+\
"uwjajsy dtzw xnxyjw kwtr wjfinsl dtzw infwd fsi tsj ymfy bnqq "+\
"uwjajsy dtzw ltajwsrjsy. ymnx nx f ajwd nrutwyfsy qjxxts yt "+\
"wjrjgjwjxujhnfqqd ktw fyyfhpx zxnsl kwjvzjshd fsfqdxnx bmnhm "+\
"wjvznwj qtsljw ufxxflj tk yjcy ns twijw yt fhmnjaj gjyyjw wjxzqyx."
FA=frequency_analysis(ciphertext)
print FA.solution


main()

Dani AI

Generated

Brief summary: the failure was not the math but the layout. In this thread the code implements a frequency-based Caesar solver, but inconsistent indentation caused assignments and loops to live outside their intended blocks, a return landed inside a loop, and the rotation step moved the wrong array. was right about the indentation; 's comment about using Numeric is also worth noting (Numeric is obsolete for a task that just needs counting). later confirms the problem was fixed.

Concrete fixes (apply in the order below):

  • Fix indentation so every function and every method body is consistently indented (use 4 spaces, do not mix tabs and spaces). Everything that belongs to __init__ must be inside that method, and each def must have its loop bodies indented beneath it.
  • Move imports to module scope (or reliably inside main() if you really want them there). Prefer built-ins: collections.Counter or list/dict arithmetic instead of Numeric unless heavy numeric work is required.
  • Ensure return statements are after loops, not inside them — the error function must accumulate across the whole loop and return once.
  • Rotate the reference-frequency list (self.cor) when testing shifts, not the observed counts array; a simple pop/insert or list-slice rotation is clearer and less error-prone.
  • Normalize counts by total letter count (sum) rather than by max frequency to get true relative frequencies, and guard against division-by-zero for empty input.

Better approach and checks: compute counts with Counter, normalize by sum, score shifts with a chi-squared or mean-squared distance, iterate all 26 rotations, and pick the smallest score. Use python -tt or a linter to catch tab/space issues, add small unit tests (short known plaintext) and print intermediate arrays while debugging.

Quick checklist: consistent 4-space indentation, imports at top, return after loops, rotate self.cor, normalize by sum, guard zeros, and replace Numeric with simple counters or NumPy if needed.

Recommended Answers

All 3 Replies

Yes, your indentations are really screwed up. In Python the code blocks that belong together need to show the same indents.

Old news, I fixed it thanks all.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.