0

I have been doing simple programming challenges all day, trying to learn and practice. I however, always seems to fail at efficiency. Without using built_in code (such as the encode method), is there anyway that I could improve my program's efficiency (my efficiency in general)?

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

スライスstr.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] # 
                )
            )

と を使用せず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'
于 2012-12-07T11:23:18.640 に答える
1

文字列フォーマットを使用すると、"%s%s" (encryption, newvalue)使用した場合と比べて 2 倍速くなり、文字列が大きくなる+=+ その差はさらに大きくなります。

Python での文字列連結と文字列置換を参照してください

于 2012-12-07T16:18:40.223 に答える
0

この方法で呼び出して、どこで時間が消費されているかを確認することは、パフォーマンスを改善するための最も基本的なツールです...

 python -m cProfile foo.py

詳しくはこちら

于 2012-12-07T09:25:23.747 に答える
0

明示的な代わりにindex += 1、たとえばfor index, letter in enumerate(alph):. これにより、コードが少し縮小され、反復インデックスが自動的に追跡されます。

于 2012-12-07T09:03:56.667 に答える