5

在我的课程中,我的任务是创建一个 Caesar Cipher 解码器,它接受输入字符串并使用字母频率找到可能的最佳字符串。如果不确定这有多大意义,请发布问题:

编写一个执行以下操作的程序。首先,它应该读取一行输入,即编码消息,由大写字母和空格组成。您的程序必须尝试使用​​移位 S 的所有 26 个可能值来解码消息;在这 26 条可能的原始消息中,打印出具有最高善意的一条。为方便起见,我们将为您预定义变量 letterGoodness,长度为 26 的列表等于上面频率表中的值

字母频率

到目前为止我有这个代码:

x = input()
NUM_LETTERS = 26 #Can't import modules I'm using a web based grader/compiler
def SpyCoder(S, N):
    y = ""
    for i in S:
        x = ord(i)
        x += N
        if x > ord('Z'):
            x -= NUM_LETTERS
        elif x < ord('A'):
            x += NUM_LETTERS
        y += chr(x)
    return y  

def GoodnessFinder(S):
    y = 0
    for i in S:
        if x != 32:
            x = ord(i)
            x -= ord('A')
            y += letterGoodness[x]
    return y 

def GoodnessComparer(S):
    goodnesstocompare = GoodnessFinder(S)
    goodness = 0
    v = ''
    for i in range(0, 26):
        v = SpyCoder(S, i)
        goodness = GoodnessFinder(v)
        if goodness > goodnesstocompare:
            goodnesstocompare = goodness
    return v

y = x.split()
z = ''
for i in range(0, len(y)):
    if i == len(y) - 1:
        z += GoodnessComparer(y[i])
print(z)

编辑:Cristian Ciupitu 建议进行更改请忽略缩进错误,它们可能是在我复制代码时出现的。

该程序的工作原理如下:

  • 获取输入并将其拆分为列表
  • 对于每个列表值,我将其提供给善良的发现者。
  • 它采用字符串的优点并将其他所有内容进行比较,当有更高的优点时,它会使更高的优点成为比较的优点。
  • 然后它将该文本字符串移动 i 量,以查看优度是更高还是更低

我不太确定问题出在哪里,第一个测试:LQKP OG CV GKIJV DA VJG BQQ
打印正确的消息:在动物园旁加入我

然而下一个测试: UIJT JT B TBNQMF MJOF PG UFYU GPS EFDSZQUJOH
给出一个垃圾字符串: SGHR HR Z RZLOKD KHMD NE SDWS ENQ CDBQXOSHMF
当它应该是: 这是一个用于解密的示例文本行

我知道我必须:
尝试每个班次值
获取单词的“善良”
返回具有最高善良的字符串。

我希望我的解释是有道理的,因为我现在很困惑。

4

4 回答 4

3

这是我的实现,效果很好。

您应该打印每条可能消息的优点并查看程序输出它的原因。

letterGoodness = dict(zip(string.ascii_uppercase,
                        [.0817,.0149,.0278,.0425,.1270,.0223,.0202,
                         .0609,.0697,.0015,.0077,.0402,.0241,.0675,
                         .0751,.0193,.0009,.0599,.0633,.0906,.0276,
                         .0098,.0236,.0015,.0197,.0007]))

trans_tables = [ str.maketrans(string.ascii_uppercase,
                 string.ascii_uppercase[i:]+string.ascii_uppercase[:i])
                 for i in range(26)]

def goodness(msg):
    return sum(letterGoodness.get(char, 0) for char in msg)

def all_shifts(msg):
    msg = msg.upper()
    for trans_table in trans_tables:
        txt = msg.translate(trans_table)
        yield goodness(txt), txt

print(max(all_shifts(input())))
于 2012-05-29T02:17:10.787 回答
2

感谢出色的 Cristian Ciupitu,我的最终解决方案可行。

x = input()
NUM_LETTERS = 26 #Can't import modules I'm using a web based grader/compiler
def SpyCoder(S, N):
   y = ""
   for i in S:
      if(i.isupper()):
         x = ord(i)
         x += N
         if x > ord('Z'):
            x -= NUM_LETTERS
         elif x < ord('A'):
            x += NUM_LETTERS
         y += chr(x)
      else:
         y += " "
   return y

def GoodnessFinder(S):
   y = 0
   for i in S:
      if i.isupper():
         x = ord(i)
         x -= ord('A')
         y += letterGoodness[x]
      else:
         y += 1
   return y

def GoodnessComparer(S):
   goodnesstocompare = GoodnessFinder(S)
   goodness = 0
   v = ''
   best_v = S
   for i in range(0, 26):
     v = SpyCoder(S, i)
     goodness = GoodnessFinder(v)
     if goodness > goodnesstocompare:
         best_v = v
         goodnesstocompare = goodness
   return best_v


print(GoodnessComparer(x))

感谢您的所有帮助!

于 2012-05-30T00:05:39.417 回答
0

我正在研究相同的教程并使用了稍微不同的方法。这避免了创建和调用函数:

inp = input()     #to hold code text
code = list(inp)  #store code as a list
soln = []         #store the 'Goodness' for each of 26 possible answers
y=0               #variable to hold total goodness during calculations
clear = []        #will hold decoded text
pos=0             #position marker for a list

#for every possible value of shift
#note range as 0 to 25 are valid shifts and shift 26 = shift 0

for shift in range(0,26):
   for i in code:                  #loop through each letter in code
      if i == " ":                 #spaces have no score so omit them
         continue
      else:                        #if it's a letter
         x = ord(i)-shift          #apply the test shift
         if x < 65:                #prevent shifting outside A-Z range
            x = x + 26             
         x = x - 64                #turn ord into character position in A-Z with A=1
         x = letterGoodness[x-1]   #turn this into the Goodness score
         y = y + x                 #add this to a running total
   soln.insert(shift-1,y)          #AFTER decoding all letters in code, add total(y) to list of scores
   y = 0                           #reset y before next test value

bestSoln=max(soln)                 #find highest possible score

for i in range(0,26):              #check the list of solutions for this score
   if soln[i]==bestSoln:           #the position in this list is the shift we need
       bestShift = i+1             #+1 as the first solution is 0

for i in code:                     #now decode the original text using our best solution
   if i == " ":                    #spaces are not encoded so just add these to the string
      clear.insert(pos," ")        #pos used to track next position for final string
      pos = pos + 1
      continue
   else:
      x = ord(i)-bestShift         #same operation as before
      if x < 65:
         x = x + 26
   z = chr(x)
   clear.insert(pos,z)             #add the decoded letter to the clear text
   pos = pos + 1
print("".join(clear))              #join the list of clear text into one string and print it

请注意,此代码的许多部分可以(并且应该)被压缩,例如

x = x - 64
x = letterGoodness[x-1]
y = y + x

它们被扩展为“展示我的工作”以进行教程练习。

于 2016-10-11T10:03:11.423 回答
0
letterGoodness = {'A': 8.17, 'B': 1.49, 'C': 2.78, 'D': 4.25, 'E': 12.70,
                  'F': 2.23, 'G': 2.02, 'H': 6.09, 'I': 6.97, 'J': 0.05, 
                  'K': 0.77, 'L': 4.02, 'M': 2.41, 'N': 6.75, 'O': 7.51, 
                  'P': 1.93, 'Q': 0.09, 'R': 5.99, 'S': 6.33, 'T': 9.06, 
                  'U': 2.76, 'V': 0.98, 'W': 2.36, 'X': 0.15, 'Y': 1.97, 
                  'Z': 0.07} 
                  
# em - input message
em = str(input()) 
em = em.upper()

# dm - guess message
dm = '' 
dmList = []
goodnessList = []
shift = 1

for g in range(25):
   goodness = 0
   dm = ''
   for i in em:
       newL = chr(ord(i) - shift)
       if i == ' ':
            dm += i

       elif ord(newL) < 65:
               A = ord(newL) + 90
               newL = chr(A - 64)
               dm += newL

       else:
            dm += newL

   for h in dm:
      if h != ' ':
         goodness += letterGoodness[h]
   goodnessList.append(goodness)
         
   shift += 1
   dmList.append(dm)  

highestG = max(goodnessList)
dmind = goodnessList.index(highestG)
print(dmList[dmind])
于 2022-01-10T20:03:15.580 回答