Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Big O notation for the str.replace function in Python?

Tags:

python

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
like image 272
Mohamad Zein Avatar asked Feb 23 '16 17:02

Mohamad Zein


People also ask

What is str replace in Python?

Python String replace() Method The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.

What is Big O notation in Python?

Big Oh Notation, Ο The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time. It measures the worst case time complexity or the longest amount of time an algorithm can possibly take to complete. Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.

Is there a Replace function in Python?

The replace() method is a built-in functionality offered in Python programming. It replaces all the occurrences of the old substring with the new substring. Replace() returns a new string in which old substring is replaced with the new substring.

Can you replace a letter in a string Python?

The Python replace() method is used to find and replace characters in a string. It requires a substring to be passed as an argument; the function finds and replaces it. The replace() method is commonly used in data cleaning.


1 Answers

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).

like image 67
Nickolay Olshevsky Avatar answered Oct 10 '22 09:10

Nickolay Olshevsky