gpt4 book ai didi

python - 如何在 python 中将字符串右移?

转载 作者:太空狗 更新时间:2023-10-29 21:16:00 30 4
gpt4 key购买 nike

我尝试将字符串向右移动

  • 最后一个值应该是第一个,其余值在后面
  • s= "I Me You" 应该返回 "You I Me"

我尝试了以下代码,但它不起作用,请帮助我......

sr= "I Me You"
def shift_right(sr):
L=sr.split()
new_list=L[-1]

new_list= new_list.append(1,L[:0])
return (new_list)

print(shift_right(sr)
print (shift_reverse(sr))

最佳答案

现在……

比赛时间

也许更有趣的是什么是更快的方法?

第一次通过 OP 测试字符串(仅 3 个 block )进行测试,第二次通过 600 个单字符 block 的字符串进行测试。

from collections import deque
import timeit

def trivial(s):
l = s.split()
return ' '.join(l[-1:] + l[:-1])

def more_split(s):
return ' '.join([s.split()[-1]] + s.split()[:-1])

def dq(s):
s_deq = deque(s.split())
s_deq.rotate(1)
return ' '.join(s_deq)

def find_and_slice(s):
lsi = s.rfind(' ')
return s[lsi+1:] + ' ' + s[:lsi]

def rs_lazy(s):
return ' '.join(reversed(s.rsplit(maxsplit=1)))

def rs_smart(s):
rs = s.rsplit(maxsplit=1)
return rs[1] + ' ' + rs[0]

def rpart(s):
part = s.rpartition(' ')
return part[-1] + part[1] + part[0]

def time_a_method(m, s):
c_arg = "('{}')".format(s)
t = timeit.timeit(m + c_arg, setup="from __main__ import " + m , number=100000)
print( m + " "*(15-len(m)) + "----> {}".format(t))


if __name__ == '__main__':
print(trivial("I Me You"))
print(more_split("I Me You"))
print(dq("I Me You"))
print(find_and_slice("I Me You"))
print(rs_lazy("I Me You"))
print(rs_smart("I Me You"))
print(rpart("I Me You"))
print("######## USE: 'I Me You'")
for m in ["trivial", "more_split", "dq", "find_and_slice", "rs_lazy", "rs_smart", "rpart"]:
time_a_method(m, "I Me You")

print("######## USE: 'a b c d e f '*100")
s = 'a b c d e f '*100
for m in ["trivial", "more_split", "dq", "find_and_slice", "rs_lazy", "rs_smart", "rpart"]:
time_a_method(m, s)

结果如下:

You I Me
You I Me
You I Me
You I Me
You I Me
You I Me
You I Me
######## USE: 'I Me You'
trivial ----> 0.1339518820000194
more_split ----> 0.1532761280000159
dq ----> 0.182199565000019
find_and_slice ----> 0.07563322400005745
rs_lazy ----> 0.23457759100006115
rs_smart ----> 0.1615759960000105
rpart ----> 0.06102836100001241
######## USE: 'a b c d e f '*100
trivial ----> 3.2239098259999537
more_split ----> 4.6946649449999995
dq ----> 3.991058845999987
find_and_slice ----> 0.15106809200005955
rs_lazy ----> 0.32278001499992115
rs_smart ----> 0.22939544400003342
rpart ----> 0.10590313199998036

赢家是......

def rpart(s):
part = s.rpartition(' ')
return part[-1] + part[1] + part[0]

这让我很吃惊(我赌 find_and_slice 但我输了)。有 2 个答案类:

  1. 蛮力:拆分所有字符串
  2. 注意我们只需要字符串的最后一部分

即使在最简单的情况下,I Me You 第一种方法也比最好的方法慢 2 到 3 倍。显然,当字符串变得更有趣时,第一种方法变得非常低效。

真正有趣的是,投票最多的答案是较慢的:)

关于python - 如何在 python 中将字符串右移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29977868/

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