Python交换一个数字中的两位数?

Rya*_*heu 2 python performance swap

在Python中用数字交换两位数的最快方法是什么?我被赋予数字作为字符串,所以如果我能有一些快速的东西,那就太好了

string[j] = string[j] ^ string[j+1] 
string[j+1] = string[j] ^ string[j+1]
string[j] = string[j] ^ string[j+1]
Run Code Online (Sandbox Code Playgroud)

我所看到的一切都比在C中要贵得多,并涉及制作一个列表然后将列表转换回来或其中的一些变体.

mar*_*eau 5

这比你想象的要快,至少比Jon Clements目前在我的计时测试中的回答要快:

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:]
Run Code Online (Sandbox Code Playgroud)

如果你想比较你得到的任何其他答案,这是我的测试床:

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)
Run Code Online (Sandbox Code Playgroud)

附录:

对于以字符串形式给出正十进制数字交换数字字符的特殊情况,以下内容也有效,并且比我答案顶部的一般版本快一点.

使用该format()方法在某种程度上涉及到转换回字符串的转换是处理零移动到字符串前面的情况.我把它主要表现为一种好奇心,因为除非你用数学方法掌握它的作用,否则它是相当难以理解的.它也不处理负数.

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)
Run Code Online (Sandbox Code Playgroud)