簡體   English   中英

如何使這個Python代碼更有效

[英]How can I make this Python code more efficient

我非常感謝您對我的第一個Python項目的反饋! :d

基本上我正在編寫一個凱撒密碼,如果你知道我的意思,我認為它非常“優化/高效”,這是因為我復制並粘貼了decrypt()方法的decrypt()方法,我唯一改變的是而不是更多地旋轉數字,我更少旋轉它們。 這就是我所說的:

       newPosition = (abc.find(letter) - key) % 26

^^ Instead of having a + (plus) I made it a - (minus) ^^

有沒有辦法可以在newPosition行調用encrypt()方法? 或者我所做的是正確的,它不需要修復(我非常懷疑)

**請記住,我從今天開始就沒有太多的Python知識(如果有的話),所以不要用一些超級復雜的代碼來吹噓我的大腦。 謝謝!!! **

abc = 'abcdefghijklmnopqrstuvwxyz'

def main():
    message = input("Would you like to encrypt or decrypt a word?")
    if message.lower() == "encrypt":
        encrypt()
    elif message.lower() == "decrypt":
        decrypt()
    else:
        print("You must enter either 'encrypt' or 'decrypt'.")
        main()


def encrypt():
    message = input("Enter a message to encrypt: ")
    message = message.lower()
    key = int(input("What number would you like for your key value?"))
    cipherText = ""
    for letter in message:
        if letter in abc:
            newPosition = (abc.find(letter) + key) % 26
            cipherText += abc[newPosition]
        else:
            cipherText += letter
    print(cipherText)
    return cipherText

def decrypt():
    message = input("Enter a message to decrypt: ")
    message = message.lower()
    key = int(input("What number would you like for your key value?"))
    cipherText = ""
    for letter in message:
        if letter in abc:
            newPosition = (abc.find(letter) - key) % 26
            cipherText += abc[newPosition]
        else:
            cipherText += letter
    print(cipherText)
    return cipherText

main()

一般來說, str.find在性能方面表現不佳。 這是O(n)的復雜性,這並不可怕,但你很少需要它。 在這種情況下,你可以使用ord將每個字母轉換為它的序數,然后減去ord('a')得到0-25而不是97-122。

這特別有用,因為您可以使用chr轉換回而無需查找。

for letter in message:
    if letter in string.ascii_lowercase:  # same as "abcdef..z"
        new_position = ((ord(letter) - ord('a') + key) % 26) + ord('a')
        new_ch = chr(new_position)
        ciphertext += new_ch

另請注意,使用+=連接字符串的速度不如str.join快。

new_letters = [chr(((ord(letter) - ord('a') + key) % 26) + ord('a')) if letter in ascii_lowercase else letter for letter in message]
ciphertext = "".join(new_letters)

因為那個chr(((ord(letter) - ord('a') + key) % 26) + ord('a'))是如此丑陋,我會把它重構成一個函數。

def rotate(letter, key=0):
    c_pos = ord(letter) - ord('a')
    rotated = c_pos + key
    modded = rotated % 26
    final_pos = modded + ord('a')
    return chr(final_pos)

new_letters = [rotate(c, key) if c in string.ascii_lowercase else c for c in letters]
ciphertext = "".join(new_letters)

可維護性:如果將輸入與結果分開,則編寫可測試的優秀代碼會更容易。 現在你必須對stdin做一些猴子修補來為你的任何函數編寫單元測試,但是如果你將用戶輸入的請求轉移到main和out各自的函數中,那就容易多了。

def main():
    message = input("What's the message to encrypt/decrypt? ")
    key = int(input("What number would you like for your key value? "))
    choice = input("Choose: encrypt or decrypt. ")
    if choice == "encrypt":
        result = encrypt(message, key)
    elif choice == "decrypt":
        result = decrypt(message, key)
    else:
        # something here about a bad user input.

事實上,當你通過翻轉鑰匙的標志來考慮Caesar Cipher是可逆的時,你可以簡單地做到:

    if choice == "encrypt":
        result = encrypt(message, key)
    elif choice == "decrypt":
        result = encrypt(message, key * (-1))

而根本不寫一個decrypt功能!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM