一般提高效率的任何提示?

时间:2012-12-07 08:57:13

标签: python

我整天都在做简单的编程挑战,试图学习和练习。然而,我似乎总是效率低下。不使用built_in代码(例如编码方法),无论如何我是否可以提高程序的效率(我的效率)?

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

4 个答案:

答案 0 :(得分: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'

答案 1 :(得分:1)

使用字符串格式"%s%s" (encryption, newvalue)比使用+=+快2倍 大字符串的差异会更大。

请参阅String concatenation vs. string substitution in Python

答案 2 :(得分:0)

您可以使用index += 1代替明确的for index, letter in enumerate(alph):。这会稍微缩小代码并自动跟踪迭代索引。

答案 3 :(得分:0)

以这种方式调用它来查看消耗时间的位置是提高性能的最基本工具......

 python -m cProfile foo.py

See here for more