2012-12-07 42 views
1

我一直在做着簡單的編程挑戰,試圖學習和實踐。然而,我總是看起來效率低下。如果沒有使用內置代碼(比如編碼方法),我是否可以提高程序的效率(通常我的效率)?提高整體效率的任何提示?

import string 
alph = string.ascii_lowercase 
def encrypt(text): 

    encryption = "" 

    for character in text: 

     index = 0 
     shift = 0 
     for letter in alph:      
      if letter == character: 

       if index > 23: 
        shift = abs(26 - (index+3)) 
        encryption += alph[shift] 
        break 
       shift = index + 3 
       encryption += alph[shift] 

      index += 1 

    return encryption 

def decrypt(text): 

    decryption = "" 

    for character in text: 

     index = 0 
     shift = 0 
     for letter in alph:      
      if letter == character: 

       if index < 3: 
        shift = abs(26 - (index+3)) 
        decryption += alph[shift] 
        break 
       shift = index - 3 
       decryption += alph[shift] 

      index += 1 

    return decryption 
+1

這是目前非常廣泛 - 它已經會更好,如果你問一些結構的效率。你雖然沒有爲你定義效率是多少(寫作時,運行時性能......),所以不可能知道正確的答案是什麼。 –

回答

0

而不是明確的index += 1比如,你可以使用for index, letter in enumerate(alph):。這會縮小代碼並自動跟蹤迭代索引。

0

調用是這樣,看看那裏的時間消耗是您提高性能的最基本的工具...

python -m cProfile foo.py 

See here for more

1

你可以使用slicesstr.maketransstr.translate(見Python.org : string) :

import string 

def rot3_encode(s): 
    return s.translate(
      string.maketrans(
       # 'abcdefghijklmnopqrstuvwxyz' 
       string.ascii_lowercase, 
       # 'defghijklmnopqrstuvwxyz' + 'abc' 
       string.ascii_lowercase[3:] + string.ascii_lowercase[:3] # 
       ) 
      ) 

沒有使用translatemaketrans

def rot3(s): 
    # 'abcdefghijklmnopqrstuvwxyz' 
    original_alphabet = string.ascii_lowercase 
    # 'defghijklmnopqrstuvwxyz' + 'abc' 
    encoded_alphabet = string.ascii_lowercase[3:] + string.ascii_lowercase[:3] 
    encoded_string = '' 
    for character in s: 
     # look at what index your character is in the original alphabet 
     encoded_string += encoded_alphabet[original_alphabet.index(character)] 
    return encoded_string 

的爲例:

rot3('afz') 
# 'a' is at index 0 of 'abcdefghijklmnopqrstuvwxyz' 
# -> you will append to your encoded string the character at index 0 of 'defghijklmnopqrstuvwxyzabc' ('d') 
# 'f' is at index 5 of 'abcdefghijklmnopqrstuvwxyz' 
# -> you will append to your encoded string the character at index 5 of 'defghijklmnopqrstuvwxyzabc' ('i') 
# ... 
>>>'dic'