2012-11-01 85 views
-1

我有两个功能。 首先将建立一个用于编码凯撒密码给定文本:如何在两个函数的python中创建一个包装?

def buildCoder(shift): 

     lettersU=string.ascii_uppercase 
     lettersL=string.ascii_lowercase 
     dic={} 
     dic2={} 

     for i in range(0,len(lettersU and lettersL)): 
      dic[lettersU[i]]=lettersU[(i+shift)%len(lettersU)] 
      dic2[lettersL[i]]=lettersL[(i+shift)%len(lettersL)] 
     dic.update(dic2) 
     return dic 

第二个将编码器应用到给定文本:问题的

def applyCoder(text, coder): 
     cipherText='' 
     for l in text: 
      if l in coder: 
       l=coder[l] 
      cipherText+=l 
     return cipherText 

第3问我构建一个包装,但由于我是编码新手,我不知道如何编写使用这两个函数的包装器。

def applyShift(text, shift): 
    """ 
    Given a text, returns a new text Caesar shifted by the given shift 
    offset. Lower case letters should remain lower case, upper case 
    letters should remain upper case, and all other punctuation should 
    stay as it is. 

    text: string to apply the shift to 
    shift: amount to shift the text (0 <= int < 26) 
    returns: text after being shifted by specified amount. 
    """ 
+1

那么你尝试过什么? –

回答

2

把你的每个函数想象成某种需要某种数据并给你一种不同的东西。

buildCoder需要shift并给你一个coder

applyCoder需要一些text(一个要编码的字符串)和一个coder,并为您提供编码字符串。

现在,你想写applyShift,一个函数,需要一个shift和一些text并给你编码的字符串。

从哪里可以得到编码字符串?仅从applyCoder。它需要textcoder。我们有text,因为它给了我们,但我们也需要coder。所以我们使用我们提供的shiftbuildCoder获得coder

总之,这将是这样的:

def applyShift(text, shift): 
    # Get our coder using buildCoder and shift 
    coder = buildCoder(shift) 
    # Now get our coded string using coder and text 
    coded_text = applyCoder(text, coder) 
    # We have our coded text! Let's return it: 
    return coded_text 
+0

我的上帝!我简直不敢相信这很简单,我猜它可能很简单,因为这部分的得分只有5.0分,而另外两个得分是15分,但从来没有我认为我比术语代码本身更受术语包装者的欢迎做了它的第一部分,但我正在考虑shift = buildCoder(shift)和text = applyCoder(文本,编码器),但没有工作。谢谢! – eraizel

1

忘掉 “包装” 一词。只需编写另一个function即可拨打另外两个电话,并返回结果。您已经获得了函数签名(它的名称和参数)以及所需结果的描述。所以在函数体中做到这一点:

  1. 呼叫buildCoder()shift参数和结果存储在变量coder
  2. 呼叫applyCoder()与你刚才保存的参数textcoder,并且将结果存储在cipher_text
  3. 返回cipher_text

要测试功能的工作原理,编写运行在您的一些测试代码一些样本数据,例如:

print applyShift('Loremp Ipsum.', 13) 
+0

谢谢你的队友!你们两个都已经清除了我的想法,正如我对包装工一词所说的那样......并没有找到像你们提供给我的有用信息! – eraizel

0
def applyShift(text, shift): 
    return applyCoder(text, buildCoder(shift)) 
相关问题