Reverse Words in a String and String Rotation in Python
In this class, we do reverse words in a string and string rotation program in python.
For Complete YouTube Video: Click Here
Reverse Words in a String
Q1) Write a program to display words in a string in reverse order. do not use split method.
The programs we discuss will help you a lot in improving coding skills. You can easily crack placement exams.
Please take our placement course for coding betterment.
To write program you should have basics on strings. Click here.
Program:
a=input("enter the string") b=len(a) end=b for j in range(b-1,-1,-1): start=j if a[j]==" ": print(a[start+1:end],end=" ") end=start print(a[start:end])
Logic:
Example: “hello this is python program”
We start at the end of the string, and we move to the beginning.
For loop, achieve this logic.
Move from the end of the string to the beginning.
If we find space character, we consider one word passed.
Display the word.
To display the word, we need to maintain positions.
We use variables start and end to maintain the position of each word.
If condition will check the character is space or not.
Using index positions, we are slicing the string and displaying words in the if condition.
After displaying each word, update the end position. to identify the next word
After coming out of the loop, the first word is not displayed.
We display the first word at the end.
String Rotation
Q2) Write a program to check string rotation.
First, understand what string rotation means.
Example:
The input string is hello.
We can do right rotation and left rotation.
String hello right rotation one time will result in ohell.
String hello right rotation two times will result in lohel.
The same way we can do left rotation.
String hello left rotation one time will result in elloh.
String hello left rotation two times will result in llohe.
The user will give two inputs. s1 and s2 strings are given.
Check s2 is the rotation of s1 or not. It may be any rotation right or left.
Logic:
Let say s1 = “hello”
we concatenate the given string with the given string. ie, we get hellohello.
You take any rotation of the given string.
Example:
String hello—> right rotation three times will result in llohe.
llohe is sub string of hellohello.
String hello —–> left rotate one-time result in ohell.
ohell is sub string of hellohello.
Take any rotation. It will be a substring to hellohello.
We use this logic.
Program:
a=input("enter the string1") b=input("enter the string2") if len(a) != len(b): print("the string2 is not rotation of string1") else: k=a+a count = k.count(b) if count >0: print("string2 is rotation of string1") else: print("string2 is not rotation of string1")
We use count method to identify occurrence of string 2.