问题
What is the big Oh notation for str.replace function in Python ?
Is it always O(n) ?
str = "this is string example"
print str.replace("is", "was")
thwas was string example
回答1:
Big O notation is calculated at worst-case scenario, and Python sources for worst case do just 'find next position of substr, replace, and go further'. One replacement does O(n) operations (copying the string). One search, according to http://effbot.org/zone/stringlib.htm, in worst-case scenario does O(n*m) operations. And since it can be up to n/m replacements, in total it should be surprisingly O(n*n).
回答2:
I coded up a test for what I believe is the worst case scenario - a string repeated over and over, and we're replacing said string with another string. Because t/n
levels off as n
increases, worst case scenario seems empirically like it may be O(n)
. But I really can't argue with @NickolayOlshevsky 's post.
import time
from matplotlib import pyplot as plt
x=[10]
while x[-1]<10**8:
x.append(int(x[len(x)-1]*1.5))
y = [0]*len(x)
nst = 'abcd'
sst = 'abcd'
for ix,i in enumerate(x):
s = ''.join([nst]*i)
t = time.time()
s = s.replace(sst,'efgh')
y[ix] = time.time()-t
x = [a*len(nst) for a in x]
%matplotlib inline
fig, (ax1,ax2) = plt.subplots(2, sharex=True)
fig.set_size_inches(8, 6)
ax1.set_xscale('log')
ax1.set_yscale('log')
ax1.set_xlabel('n')
ax1.set_ylabel('t')
ax1.plot(x,y)
ax2.set_xscale('log')
ax2.set_yscale('log')
ax2.set_xlabel('n')
ax2.set_ylabel('t/n')
ax2.plot(x,[a/b for a,b in zip(x,y)])
来源:https://stackoverflow.com/questions/35583983/what-is-the-big-o-notation-for-the-str-replace-function-in-python