Reverse a Sentence and String Comprehension with same logic in Python 3
return " ".join(reversed(a.split()))
return " ".join(a.split()[::-1])
words = []
length = len(a)
i = 0
while i<length:
if a[i] != " ":
word_start = i
while i<length and a[i] != " ":
i+=1
words.append(a[word_start:i])
i+=1
return " ".join(reversed(words))
935 ns per loop
%timeit reversed_sentence2("Hello World! How are you?")
710 ns per loop
%timeit reversed_sentence3("Hello World! How are you?")
5.54 ยตs per loop
Reverse a Sentence
Solution 1: Using Split & Reverse
def reversed_sentence(a):return " ".join(reversed(a.split()))
Solution 2: Using Split and Index
def reversed_sentence2(a):return " ".join(a.split()[::-1])
Solution 3: Without using inbuilt functions | Double While Loop
def reversed_sentence3(a):words = []
length = len(a)
i = 0
while i<length:
if a[i] != " ":
word_start = i
while i<length and a[i] != " ":
i+=1
words.append(a[word_start:i])
i+=1
return " ".join(reversed(words))
Test
%timeit reversed_sentence("Hello World! How are you?")935 ns per loop
%timeit reversed_sentence2("Hello World! How are you?")
710 ns per loop
%timeit reversed_sentence3("Hello World! How are you?")
5.54 ยตs per loop
String Compression - AAABBBCCDEeeEaaBB to A3B3C2DEe2Ea2B2
def compress_string(s):
compress = []
i=0
length = len(s)
while i < length:
letter = s[i]
count = 0
while i < length and letter==s[i]:
count+=1
i+=1
if count == 1:
compress.append(letter)
else:
compress.append(letter+str(count))
return "".join(compress)
Test
%timeit compress_string("AAABBBCCDEeeEaaBB")
6.98 ยตs per loop
compress_string("AAABBBCCDEeeEaaBB")
'A3B3C2DEe2Ea2B2'
Comments
Post a Comment