Program for Reversed String Pattern
Given a string str as the input. The task is to print the pattern as shown in the example.
Examples:
Input : str = “geeks”
Output :
g
e e
* s k
Explanation :
In the first line print the first character in the string.
In the second line print the next two characters in reverse order.
In the third line there are not enough characters to print so append *s and print the characters in reverse order.Input: str = “orange”
Output:
o
a r
e g n
Approach:
- Initialize an empty list and a variable x with value 1.
- Traverse through the input string str and append the characters to the list.
- If the length of the list is equal to the value of x then
- Print the characters in the list in reverse order.
- Increment the value of x by 1.
- Empty the list
- If the length of the last printed characters is not 0 and it is less than the value of x then append x-length(x) *s and print it in reverse order.
# function to print the pattern def reverseString(str): # initialize an empty list r = [] # initialize the value of x as 1 x = 1 # traverse through all the characters of x for i in str: # append all the characters to the list r.append(i) # if the length of the list is x if len(r)== x: # print the list in revere order print(*reversed(r)) # increment the value of x x+= 1 # empty the list r = [] # if the list is not empty # length of the list is less than x if len(r)<x and len(r)!= 0: # print x-len(r) *s and the reversed list print('* ' * (x-len(r)), *reversed(r)) # get the input string str = "geeks" # calling the function to print the pattern reverseString(str) |
g e e * s k
Recommended Posts:
- Check if a string follows a^nb^n pattern or not
- Printing string in plus ‘+’ pattern in the matrix
- Count of occurrences of a "1(0+)1" pattern in a string
- Program to print the pattern 'G'
- Program to print the pattern ‘D’
- Check if string follows order of characters defined by a pattern or not | Set 3
- Check if string follows order of characters defined by a pattern or not | Set 2
- Check if string follows order of characters defined by a pattern or not | Set 1
- Python | Get the smallest window in a string containing all characters of given pattern
- Python | Reversed Split Strings
- Program to print Step Pattern
- Program to print the Zigzag pattern
- Python | Reversed Order keys in dictionary
- Python Program to print digit pattern
- Program to Print Pyramid Pattern using numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



