Day 8 - Beginner - Function Parameters & Caesar Cipher

Day 8 - Beginner - Function Parameters & Caesar Cipher

  1. Day 8 Goals: what we will make by the end of the day
  2. Functions with Inputs
  3. Positional vs. Keyword Arguments
  4. [Interactive Coding Exercise] Paint Area Calculator
  5. [Interactive Coding Exercise] Prime Number Checker
  6. Caesar Cipher Part 1 - Encryption
  7. Caesar Cipher Part 2 - Decryption
  8. Caesar Cipher Part 3 - Reorganising our Code
  9. Caesar Cipher Part 4 - User Experience Improvements & Final Touches
  10. How You Can Stay Motivated

這一天的課程,筆記還是在 repl.it 上。

但從 83. Caesar Cipher 開始的課程上,我是覺得老師把字典 alphabet[…] list
內容重覆 2 組的作法不以為然。要是字典內容不是英文字母,而是7000中文字怎麼辦?也要重覆2組嗎?
所以我從一開就以一組字典為基礎來寫程式,不過解題方式大致是相同的,只是左右shift的數字不一樣。

想 challenge 的,也可以考慮不照老師方式來試試看。

2個讚

你可以分享用一組alphabet寫出來的程式長怎樣嗎?怎麼克服overrange的問題?

以下請參考!若有錯誤,還請不吝指正,謝謝!
encode decode 要 key 對,否則會錯。
沒多作優化,算是交差了事。

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
            'v', 'w', 'x', 'y', 'z']

### 我的解法 ###
def caesar(org_text, org_shift, sel_direction):
    alpha_length = len(alphabet)  # 26個字母

    code_data = ""  # 設初值為空字串,非list[]. list的數據項不需要具有相同的類型,字串則僅為字串。

    if org_shift > alpha_length:  # 檢查 shift 若大於26個字母,則取除 26 之餘數
        org_shift = org_shift % alpha_length

    org_text_index = 0
    for x in org_text:  # 逐字母encode decode(本處有修正,以下 alphabe.index(x)同)
        if x in alphabet:
            if sel_direction == "encode":
                org_text_index = alphabet.index(x) + org_shift  # alphabet.index(x) 求 x 在 list 中之 index
                if org_text_index > (alpha_length - 1):  # 向右 shift 超出 index[25]
                    org_text_index = org_text_index - alpha_length  # 向左 shift 一輪
            elif sel_direction == "decode":
                org_text_index = alphabet.index(x) - org_shift  # alphabet.index(x) 求 x 在 list 中之 index
                if org_text_index < 0:  # 向左 shift 超出 index[0]
                    org_text_index = org_text_index + alpha_length  # 向右 shift 一輪
            code_data += alphabet[org_text_index]
        else:  # 找不到字母則不處理,原字加回。
            code_data += x

    print(f"The {sel_direction}d text is {code_data}")


from art import logo

print(logo)

is_continue = True
while is_continue:

    direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
    text = input("Type your message:\n").lower()
    shift = int(input("Type the shift number:\n"))

    caesar(text, shift, direction)

    restart = input("Type 'yes' if you want to go again. Otherwise type 'no'.\n")
    if restart == "no":
        is_continue = False
        print("Goodbye")
2個讚

謝謝r大分享