Reputation: 2277
I am trying to make a program that reverses each words, but not reverses words in tags.
Example input and output:
Input:
Thank you stack overflow
Output:
knahT uoy kcats wolfrevo
If the word is in tags, it should be not reversed. Like this:
Input:
<tag>something
Ouput:
<tag>gnihtemos
I tried to solve this using stack algorithm.
s = input()
def stackprint(st):
while st != []:
print(st.pop(), end="")
stack = []
tag = False
for ch in s:
if ch == '<':
stackprint(stack)
tag = True
print(ch, end="")
elif ch == '>':
tag = False
print(ch, end="")
elif tag:
print(ch, end="")
else:
if ch == ' ':
stackprint(stack)
print(ch, end="")
else:
stack.append(ch)
print("".join(stack))
But, my code is not working if there is only one word or there is no tag. When there is no tag, the last word is not reversed, and when there is only one word, it doesn't get reversed.
The output now:
First
When Input:
<tag>something
Ouput:
<tag>something
^ I need something to be reversed.
Second
Input:
Thank you stack overflow
Ouput:
knahT uoy kcats overflow
^ I need overflow to be reversed.
I need whatever inside < > should be not reversed. If the word is in tags, it should be not reversed like input:
<tag>word<tag>
output:
<tag>drow<tag>
There will be no space between a tag and a word.
Thank you <tag>stack overflow
knahT uoy <tag>kcats wolfrevo
Upvotes: 3
Views: 113
Reputation: 320
As I've mentioned in the comment section, instead of printing the stack with the join method, calling the stackprint method to ensure that the stack is emptied will give you the desired result.
s = input()
def stackprint(st):
while st != []:
print(st.pop(), end="")
stack = []
tag = False
for ch in s:
if ch == '<':
stackprint(stack)
tag = True
print(ch, end="")
elif ch == '>':
tag = False
print(ch, end="")
elif tag:
print(ch, end="")
else:
if ch == ' ':
stackprint(stack)
print(ch, end="")
else:
stack.append(ch)
stackprint(stack)
Upvotes: 1
Reputation: 1526
This seems to work with the examples you have provided:
def revSetence(sentence):
sentence = sentence + " ";
flag = False
final_sentence = ""
word = ""
for letter in sentence:
if letter == "<":
flag = True
if letter == ">":
flag = False
if letter.isalpha():
if flag:
final_sentence = final_sentence + letter
else:
word = word + letter
else:
if len(word) > 0:
final_sentence = final_sentence + word[::-1]
final_sentence = final_sentence + letter
word =""
return final_sentence
Upvotes: 1