-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreverseASentence.py
More file actions
48 lines (38 loc) · 1.09 KB
/
reverseASentence.py
File metadata and controls
48 lines (38 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import timeit
def splitSentence(sentence):
indexList = []
wordsList = []
for i in range(len(sentence)):
if sentence[i] == ' ':
indexList.append(i)
i = 0
j = 0
for i in indexList:
wordsList.append(sentence[j:i])
j = i+1
wordsList.append(sentence[j:len(sentence)])
return wordsList
def reverseSentence(sentence):
i = 0
j = len(sentence) - 1
while i < j:
sentence[i],sentence[j] = sentence[j],sentence[i]
i += 1
j -= 1
return sentence
def joinSentence(sentence):
finalSentence = ''
for i in sentence:
finalSentence += i
finalSentence += ' '
return finalSentence
def main():
sentence = 'I have successfully programmed this problem'
print('Given Sentence:',sentence)
wordsList = splitSentence(sentence)
reverseWords = reverseSentence(wordsList)
reversedSentence = joinSentence(reverseWords)
print('Reversed Sentence:',reversedSentence)
if __name__ == '__main__':
t = timeit.Timer(lambda:main())
print('Time Taken:',t.timeit(number=1),'seconds')