gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:26:20 30 4
gpt4 key购买 nike

在 Python 中交换数字中两位数字的最快方法是什么?我得到的是字符串形式的数字,所以如果我能像

string[j] = string[j] ^ string[j+1] 
string[j+1] = string[j] ^ string[j+1]
string[j] = string[j] ^ string[j+1]

我所见过的一切都比用 C 语言昂贵得多,并且涉及创建一个列表,然后将列表转换回列表或其某些变体。

最佳答案

这比您想象的要快,至少比 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:]

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

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() 方法在最后转换回字符串是为了处理将零移到字符串前面的情况。我提出它主要是出于好奇,因为除非您掌握它在数学上的作用,否则它是相当难以理解的。它也不处理负数。

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)

关于Python交换一个数字中的两位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13040891/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com