2012-11-01 143 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)) 
相關問題