이것은 당신이 생각하는 것보다 더 빠르다는, 적어도 내 타이밍 테스트 존 클레멘트의 현재 답변을보다 더 빠르게 :
i, j = (i, j) if i < j else (j, i) # make sure i < j
s = s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:]
가 여기 내 테스트 베드의 당신은 당신이 얻을 다른 답변을 비교하고자한다 :
양의 진수 gi에서 숫자 문자를 교환의 특별한 경우를 들어
:
import timeit
import types
N = 10000
R = 3
SUFFIX = '_test'
SUFFIX_LEN = len(SUFFIX)
def setup():
import random
global s, i, j
s = 'abcdefghijklmnopqrstuvwxyz'
i = random.randrange(len(s))
while True:
j = random.randrange(len(s))
if i != j: break
def swapchars_martineau(s, i, j):
i, j = (i, j) if i < j else (j, i) # make sure i < j
return s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:]
def swapchars_martineau_test():
global s, i, j
swapchars_martineau(s, i, j)
def swapchars_clements(text, fst, snd):
ba = bytearray(text)
ba[fst], ba[snd] = ba[snd], ba[fst]
return str(ba)
def swapchars_clements_test():
global s, i, j
swapchars_clements(s, i, j)
# find all the functions named *SUFFIX in the global namespace
funcs = tuple(value for id,value in globals().items()
if id.endswith(SUFFIX) and type(value) is types.FunctionType)
# run the timing tests and collect results
timings = [(f.func_name[:-SUFFIX_LEN],
min(timeit.repeat(f, setup=setup, repeat=R, number=N))
) for f in funcs]
timings.sort(key=lambda x: x[1]) # sort by speed
fastest = timings[0][1] # time fastest one took to run
longest = max(len(t[0]) for t in timings) # len of longest func name (w/o suffix)
print 'fastest to slowest *_test() function timings:\n' \
' {:,d} chars, {:,d} timeit calls, best of {:d}\n'.format(len(s), N, R)
def times_slower(speed, fastest):
return speed/fastest - 1.0
for i in timings:
print "{0:>{width}}{suffix}() : {1:.4f} ({2:.2f} times slower)".format(
i[0], i[1], times_slower(i[1], fastest), width=longest, suffix=SUFFIX)
부록 벤은 문자열로, 다음은 또한 작품과 내 대답 맨 위에 일반 버전보다 조금 빨리입니다.
format()
메서드를 사용하여 끝에 문자열로 다소 복잡한 변환을 수행하면 0이 문자열 앞쪽으로 이동 한 경우를 처리 할 수 있습니다. 수학적으로 무엇을하는지 이해하지 못한다면 이해하기 힘들 기 때문에 주로 호기심으로 제시합니다. 또한 음수를 처리하지 않습니다.
n = int(s)
len_s = len(s)
ord_0 = ord('0')
di = ord(s[i])-ord_0
dj = ord(s[j])-ord_0
pi = 10**(len_s-(i+1))
pj = 10**(len_s-(j+1))
s = '{:0{width}d}'.format(n + (dj-di)*pi + (di-dj)*pj, width=len_s)
어떤 숫자를 바꿔야합니까? – raina77ow
여기서 가변 유형과의 변환을 피할 수 없습니다. ['array'] (http://docs.python.org/library/array.html) 모듈을 사용해 볼 수도 있지만, 더 빠를 것이라고 보증 할 수는 없습니다. – millimoose
내가 아는가요
Neil