Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Reverse the string word
#1
Hello friends,
I am trying to reverse the words present in the string(for eg. I am a student output:student a am I) . I have reference code but i did not understand the exact working of code. can anyone please explain me the working of the code. I am the beginner in the coding.

Here is my code :

def wordReverse(str): 
	i = len(str)-1
	start = end = i+1
	result = '' 

	while i>=0: 
		if str[i] == ' ': 
			start = i+1
			while start!= end: 
				result += str[start] 
				start+=1
			result+=' '
			end = i 
		i-=1
	start = 0
	while start!=end: 
		result+=str[start] 
		start+=1
	return result 

# Driver Code 
str = 'I AM A GEEK'
print(wordReverse(str))
buran wrote Dec-10-2019, 03:25 PM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Quote
#2
The code assesses the sentence from the end to the beginning. The first while loop checks each character starting from the end until it finds a space. Once it finds a space, it iterates from the index start until index end and writes the word to the result. Then, it continues. The last loop basically does the same thing as the first one to pick up the first word in the original sentence.

Now, this can be written more concisely in Python.

def wordReverse(str): 
    words = str.split() # Split sentence by spaces into a list
    return " ".join(words[::-1])
Quote
#3
Thank you for help.
Now i completely understand the code.. Thank you sir.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Cannot Remove the Double Quotes on a Certain Word (String) Python BeautifulSoup soothsayerpg 5 384 Oct-27-2019, 09:53 AM
Last Post: newbieAuggie2019
  print a word after specific word search evilcode1 8 221 Oct-22-2019, 08:08 AM
Last Post: newbieAuggie2019
  is there a reverse index? Skaperen 6 509 Jun-14-2019, 11:47 PM
Last Post: Skaperen
  String slicing in python from reverse ift38375 1 362 Apr-29-2019, 06:58 AM
Last Post: perfringo
  Word replace with string dabozz 1 419 Feb-13-2019, 03:11 PM
Last Post: ichabod801
  Reverse word xSphere 4 679 Jan-28-2019, 11:43 AM
Last Post: perfringo
  Replacing all letters in a string apart from the first letter in each word Carbonix 9 1,027 Jan-17-2019, 09:29 AM
Last Post: buran
  Creating list out of the first letter of every word in a string Drone4four 5 6,968 Oct-05-2018, 09:42 PM
Last Post: volcano63
  reverse generator Skaperen 7 3,460 Apr-23-2018, 03:10 AM
Last Post: Skaperen
  difference between word: and word[:] in for loop zowhair 2 935 Mar-03-2018, 07:24 AM
Last Post: zowhair

Forum Jump:


Users browsing this thread: 1 Guest(s)