2012-06-01 4 views
0

이 프로그램은 파이썬의 기본 엔코더이며 정의 된 변수의 이름을 변경하지 않고도 더 효율적으로 만들 수 있는지 알고 싶습니다. 누군가 제안 해 줄 수 있습니까?이 프로그램을보다 효율적으로 만들 수있는 방법

def encode(pattern, filename): 
    f = open(filename, "rt") 
    contents = f.read() 
    f.close() 
    printNow(contents) 

    changes = pattern.split("|") 
    for str in changes: 
    printNow("Change "+ str[0] + " to " + str[1]) 

    newMsg = "" 
    for char in contents: 
    for change in changes: 
     if char == change [0]: 
     char = change[1] 
    newMsg += char 



    f = open(filename + "encoded", "wt") 
    f.write(newMsg) 
    f.close() 

    f = open(filename + "encoded", "rt") 
    printNow(f.read()) 
    f.close() 

encode("ae|ga|s3", "C:\\Users\\Shaun\\Desktop\\Test.txt") 
+1

당신이해야한다고 생각하는만큼 성과가 좋지 않은 곳. – Jordan

+0

보다 효율적으로 무엇을 의미합니까? 좀 더 구체적이어야합니다. Efficient의 정의는 사람마다 다른데, 실행 시간, 메모리 소비 또는 출력입니까 ?? – Zeina

답변

1

사용 str.translate() 대신 어려운 방법으로 모두 교체하고, 그것을 한 줄 한 줄 않습니다의.

3
import string 


def encode(pattern, filename): 
    with open(filename) as f: 
     contents = f.read() 
    s = string.maketrans(*[''.join(a) for a in zip(*pattern.split('|'))]) 
    newMsg = contents.translate(s) 
    with open(filename + 'encoded', 'rt') as f: 
     f.write(newMsg) 
0

먼저 알고리즘이 이미 충분하다는 옵션을 고려해야합니다. 최적화 할 수 있다고해도 코드가 더 큰 프로그램의 일부이고 0.1 %의 시간 동안 만 실행되는 경우 예를 들어 프로그램의 나머지 부분이 코드를 독점하기 때문에 코드를 최적화하는 데는 거의 쓸모가 없습니다. 총 실행 시간.

코드에 실제로 문제가있는 경우 알고리즘의 complexity을 분석하여 시작합니다.

마지막으로 코드에서 병목 현상을 찾을 수 있습니다. 이를 위해 Python의 timeit과 같은 코드로 프로파일을 작성합니다. 방법은 여기에 문자 대체를 위해 잘 작동하지만,()

0

str.translate은 멀티 문자 대체 작동 내가 사용했던 다른 빠른 방법 :

import re 

def encode(pattern, filename): 
    f = open(filename, "rt") 
    contents = f.read() 
    f.close() 
    printNow(contents) 

    change_dict = {} 
    matches = [] 
    changes = pattern.split("|") 
    for str in changes: 
    printNow("Change "+ str[0] + " to " + str[1]) 
    change_dict[str[0]] = str[1] 
    matches.append(str[0]) 

    change_re = re.compile("|".join(re.escape(x) for x in matches)) 

    newMsg = change_re.sub(lambda m: change_dict[m.group(0)], contents) 

    f = open(filename + "encoded", "wt") 
    f.write(newMsg) 
    f.close() 

    f = open(filename + "encoded", "rt") 
    printNow(f.read()) 
    f.close() 

encode("ae|ga|s3", "C:\\Users\\Shaun\\Desktop\\Test.txt") 
당신은 그것을 측정하고 우리에게 말하고으로 시작할 수
관련 문제