0

我整天都在做简单的编程挑战,努力学习和实践。然而,我似乎总是在效率上失败。如果不使用内置代码(例如 encode 方法),我是否可以提高程序的效率(我的一般效率)?

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

4 回答 4

1

与 using 相比,使用字符串格式化"%s%s" (encryption, newvalue)要快 2 倍,+=而且+ 使用更大的字符串时差异会更大。

请参阅Python 中的字符串连接与字符串替换

于 2012-12-07T16:18:40.223 回答
1

您可以使用slicesstr.maketrans, str.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] # 
                )
            )

不使用translateand maketrans

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'
于 2012-12-07T11:23:18.640 回答
0

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

于 2012-12-07T09:03:56.667 回答
0

以这种方式调用它以查看时间消耗在哪里是您提高性能的最基本工具......

 python -m cProfile foo.py

看这里了解更多

于 2012-12-07T09:25:23.747 回答