How change the cycle for getting correct answers? - python

I have a task to create a function that reverse any string character inside the regular bracket sequence, starting from the innermost pair. The string sequence can have, spaces, punctuation marks, letters and brakets. So the result should be sting.
Example
For string
s = "a(bc)de"
the output should be
reverseParentheses(s) = "acbde".
I have wrote the following code to solve this problem:
s_i = s
for i in range(s.count('(')):
# reverse letters inside parenthesis
s_i = s_i.replace(s_i[s_i.rindex('(')+1:s_i.index(')')], s_i[s_i.rindex('(')+1:s_i.index(')')][::-1])
# delete outward parenthesis
s_i =s_i[:s_i.rindex('(')] + s_i[s_i.rindex('(')+1:]
# delete inward parenthesis
s_i =s_i[:s_i.index(')')] + s_i[s_i.index(')')+1:]
i += 1
print(s_i)
However, I become false results for following strings:
s = "abc(cba)ab(bac)c"
It should be
abcabcabcabc
I get
abccabbaabcc
And
s = "The ((quick (brown) (fox) jumps over the lazy) dog)"
It should be like this:
The god quick nworb xof jumps over the lazy
But I get only:
The god quick xof nworb jumps over the lazy
How should I correct or adjust my code for becoming right results for last two examples?
Code Adjustment
I have tried to take into consideration answers and hints but I could not use recursion. I adressed the problem with the parantacies when there are just two of them located as: "..(...) (...).., .."
So I made the following code:
def reverse(s):
#ensure parens are in pairs
if '(' not in s and ')' not in s:
while '(' in s:
s = s.replace(s[s.rindex('(')+1:s.index(')')], s[s.rindex('(')+1:s.index(')')][::-1])
s = s[:s.rindex('(')] + s[s.rindex('(')+1:]
s = s[:s.index(')')] + s[s.index(')')+1:]
return s
else:
if (s[s.index(')'):s.rindex('(')+1] == ''):
while '(' in s:
s = s.replace(s[s.rindex('(')+1:s.index(')')], s[s.rindex('(')+1:s.index(')')][::-1])
s = s[:s.rindex('(')] + s[s.rindex('(')+1:]
s = s[:s.index(')')] + s[s.index(')')+1:]
return s
elif (s[s.index(')'):s.rindex('(')+1] != ''):
betw = s[s.index(')')+1:s.rindex('(')]
part1 = s[:s.index(')')+1]
part2 = s[s.rindex('('):]
part1 = part1.replace(part1[part1.rindex('(')+1:part1.index(')')], part1[part1.rindex('(')+1:part1.index(')')][::-1])
part1 = part1[:part1.rindex(')')]
part2 = part2.replace(part2[part2.rindex('(')+1:part2.index(')')], part2[part2.rindex('(')+1:part2.index(')')][::-1])
part2 = part2[part2.rindex('(')+1:]
s = part1+betw+part2
s = s[:s.rindex('(')] + s[s.rindex('(')+1:]
s = s[:s.index(')')] + s[s.index(')')+1:]
while '(' in s:
s = s.replace(s[s.rindex('(')+1:s.index(')')], s[s.rindex('(')+1:s.index(')')][::-1])
s = s[:s.rindex('(')] + s[s.rindex('(')+1:]
s = s[:s.index(')')] + s[s.index(')')+1:]
return s
else:
while '(' in s:
s = s.replace(s[s.rindex('(')+1:s.index(')')], s[s.rindex('(')+1:s.index(')')][::-1])
s = s[:s.rindex('(')] + s[s.rindex('(')+1:]
s = s[:s.index(')')] + s[s.index(')')+1:]
return s
However, I think that it can not perform well for the following example:
s = "abc(147)ab(123)c(12)asd"
The answer should be: "abc741ab321c21asd" but I get "abc12c321ba147asd"
What should be changed in order to get the correct answer?

rather than doing this manually, use the regular expression module re that specialize in string manipulation
import re
def reverseParentheses(s):
def reverse_interior(m):
s = m.group()
return s[-2:0:-1]
old = ""
while old != s:
old = s
s = re.sub(r'(\([^\(\)]*\))',reverse_interior,s)
return s
assert reverseParentheses("a(bc)de") == "acbde"
assert reverseParentheses("abc(cba)ab(bac)c") == "abcabcabcabc"
assert reverseParentheses("The ((quick (brown) (fox) jumps over the lazy) dog)") == "The god quick nworb xof jumps over the lazy"
assert reverseParentheses("((ob))") == "ob"
here the expression '(\([^\(\)]*\))' would search anything that is between ( and ) that is a one of characters defined in [^\(\)]* which in turn means any numbers character that is not a ( or ), this way it will search the innermost group that match, then I use the function re.sub to replace those in the string with that auxiliary function, that take a string of the form "(xyz)" and return "zyx". As this only work for the innermost group, the process should be repeated while there are changes to be made, hence the loop.

The reason your solution isn't working is because it is mismatching parentheses:
"abc(cba)ab(bac)c"
" (cba)ab(bac) "
" )ab( "
Your method ultimately won't work: Instead, I recommend you figure out a better way of figuring out which parens match:
def find_paren_set(str):
# magic
return left, right
Once you have that capability, you can then just while has_parens(str): through until you're done.
Additional note: Each time you reverse a section, the inner parens will get swapped, ((ob)) will become )bo(.

Since it appears that any number of () pairs could occur, I would recommend implementing a recursive function that can be called as long as pairs of parens still exist at a level outside the first:
def reverseParentheses(s):
# ensure parens are in pairs
assert '(' in s and ')' in s
while '(' in s:
# Go through and swap strings/letters in the innermost parens only.
# Then reassign `s` to that newly formatted string
# (after taking out those parens)
# Call the function again until it purges the string of all parens
reverseParentheses(s)
return s

Related

python Question: Could any one explain how the above class reversed the string return val? sorry coming back to python after many years [duplicate]

I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
n = n + 1
result = s[ start: n ] + " " + result
start = n
return result
But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much.
Any help would be appreciated.
def rreverse(s):
if s == "":
return s
else:
return rreverse(s[1:]) + s[0]
(Very few people do heavy recursive processing in Python, the language wasn't designed for it.)
To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself.
What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, right?
So the reverse of a string is the last character, followed by the reverse of everything but the last character, which is where the recursion comes in. The last character of a string can be written as x[-1] while everything but the last character is x[:-1].
Now, how do you "bottom out"? That is, what is the trivial case you can solve without recursion? One answer is the one-character string, which is the same forward and reversed. So if you get a one-character string, you are done.
But the empty string is even more trivial, and someone might actually pass that in to your function, so we should probably use that instead. A one-character string can, after all, also be broken down into the last character and everything but the last character; it's just that everything but the last character is the empty string. So if we handle the empty string by just returning it, we're set.
Put it all together and you get:
def backward(text):
if text == "":
return text
else:
return text[-1] + backward(text[:-1])
Or in one line:
backward = lambda t: t[-1] + backward(t[:-1]) if t else t
As others have pointed out, this is not the way you would usually do this in Python. An iterative solution is going to be faster, and using slicing to do it is going to be faster still.
Additionally, Python imposes a limit on stack size, and there's no tail call optimization, so a recursive solution would be limited to reversing strings of only about a thousand characters. You can increase Python's stack size, but there would still be a fixed limit, while other solutions can always handle a string of any length.
I just want to add some explanations based on Fred Foo's answer.
Let's say we have a string called 'abc', and we want to return its reverse which should be 'cba'.
def reverse(s):
if s == "":
return s
else:
return reverse(s[1:]) + s[0]
s = "abc"
print (reverse(s))
How this code works is that:
when we call the function
reverse('abc') #s = abc
=reverse('bc') + 'a' #s[1:] = bc s[0] = a
=reverse('c') + 'b' + 'a' #s[1:] = c s[0] = a
=reverse('') + 'c' + 'b' + 'a'
='cba'
If this isn't just a homework question and you're actually trying to reverse a string for some greater goal, just do s[::-1].
def reverse_string(s):
if s: return s[-1] + reverse_string(s[0:-1])
else: return s
or
def reverse_string(s):
return s[-1] + reverse_string(s[0:-1]) if s else s
I know it's too late to answer original question and there are multiple better ways which are answered here already. My answer is for documentation purpose in case someone is trying to implement tail recursion for string reversal.
def tail_rev(in_string,rev_string):
if in_string=='':
return rev_string
else:
rev_string+=in_string[-1]
return tail_rev(in_string[:-1],rev_string)
in_string=input("Enter String: ")
rev_string=tail_rev(in_string,'')
print(f"Reverse of {in_string} is {rev_string}")
s = input("Enter your string: ")
def rev(s):
if len(s) == 1:
print(s[0])
exit()
else:
#print the last char in string
#end="" prints all chars in string on same line
print(s[-1], end="")
"""Next line replaces whole string with same
string, but with 1 char less"""
return rev(s.replace(s, s[:-1]))
rev(s)
if you do not want to return response than you can use this solution. This question is part of LeetCode.
class Solution:
i = 0
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if self.i >= (len(s)//2):
return
s[self.i], s[len(s)-self.i-1] = s[len(s)-self.i-1], s[self.i]
self.i += 1
self.reverseString(s)

How do I reverse the strings contained in each pair of matching parentheses, starting from the innermost pair? CodeFights

So far I have done this. I am stuck on recursion. I have no idea how to move forward, joining and reversing etc.
def callrecursion(s):
a=s.index('(')
z=len(s) - string[::-1].index(')') -1
newStr=s[a+1:z]
# Something is missing here i cant figure it out
print(newStr)
return newStr
def reverseParentheses(s):
if '(' in s:
return reverseParentheses(callrecursion(s))
print('wabba labba dub dub')
else:
return s
string='a(bcdefghijkl(mno)p)q'
reverseParentheses(string)
EXPECTED OUTPUT : "apmnolkjihgfedcbq"
def reverseParentheses(s):
if '(' in s:
posopen=s.find('(')
s=s[:posopen]+reverseParentheses(s[posopen+1:])
posclose=s.find(')',posopen+1)
s=s[:posopen]+s[posopen:posclose][::-1]+s[posclose+1:]
return s
string='a(bcdefghijkl(mno)p)q'
print(string)
print(reverseParentheses(string))
print('apmnolkjihgfedcbq') # your test
string='a(bc)(ef)g'
print(string)
print(reverseParentheses(string))
The idea is to go 'inward' as long as possible (where 'inward' does not even mean 'nesting', it goes as long as there are any opening parentheses), so the innermost pairs are flipped first, and then the rest as the recursion returns. This way 'parallel' parentheses seem to work too, while simple pairing of "first opening parentheses" with "last closing ones" do not handle them well. Or at least that is what I think.
Btw: recursion is just a convoluted replacement for rfind here:
def reverseParentheses(s):
while '(' in s:
posopen=s.rfind('(')
posclose=s.find(')',posopen+1)
s=s[:posopen]+s[posopen+1:posclose][::-1]+s[posclose+1:]
return s;
(... TBH: now I tried, and the recursive magic dies on empty parentheses () placed in the string, while this one works)
I've come up with tho following logic (assuming the parentheses are properly nested).
The base case is the absence of parentheses in s, so it is returned unchanged.
Otherwise we locate indices of leftmost and rightmost opening and closing parentheses
(taking care of possible string reversal, so ')' might appear opening and '(' -- as closing).
Having obtained beg and end the remaining job is quite simple: one has to pass the reversed substring contained between beg and end to the subsequent recursive call.
def reverseParentheses(s):
if s.find('(') == -1:
return s
if s.find('(') < s.find(')'):
beg, end = s.find('('), s.rfind(')')
else:
beg, end = s.find(')'), s.rfind('(')
return s[:beg] + reverseParentheses(s[beg + 1:end][::-1]) + s[end + 1:]
Assuming that number of opening and closing brackets always match, this might be the one of the simplest method to reverse words in parenthesis:
def reverse_parentheses(st: str) -> str:
while True:
split1 = st.split('(')
split2 = split1[-1].split(')')[0]
st = st.replace(f'({split2})', f'{split2[::-1]}')
if '(' not in st and ')' not in st:
return st
# s = "(abcd)"
# s = "(ed(et)el)"
# s = "(ed(et(oc))el)"
# s = "(u(love)i)"
s= "((ng)ipm(ca))"
reversed = reverse_parentheses(s)
print(reversed)
You have a few issues in your code, and much of the logic missing. This adapts your code and produces the desired output:
def callrecursion(s):
a=s.index('(')
# 's' not 'string'
z=len(s) - s[::-1].index(')') -1
newStr=s[a+1:z][::-1]
# Need to consider swapped parentheses
newStr=newStr.replace('(', "$") # Placeholder for other swap
newStr=newStr.replace(')', "(")
newStr=newStr.replace('$', ")")
#Need to recombine initial and trailing portions of original string
newStr = s[:a] + newStr + s[z+1:]
return newStr
def reverseParentheses(s):
if '(' in s:
return reverseParentheses(callrecursion(s))
print('wabba labba dub dub')
else:
return s
string='a(bcdefghijkl(mno)p)q'
print(reverseParentheses(string))
>>>apmnolkjihgfedcbq
While the existing O(n^2) solutions were sufficient here, this problem is solvable in O(n) time, and the solution is pretty fun.
The idea is to build a k-ary tree to represent our string, and traverse it with DFS. Each 'level' of the tree represents one layer of nested parentheses. There is one node for each set of parentheses, and one node for each letter, so there are only O(n) nodes in the tree.
For example, the tree-nodes at the top level are either:
A letter that is not contained in parentheses
A tree-node representing a pair of parentheses at the outermost layer of our string, which may have child tree-nodes
To get the effect of reversals, we can traverse the tree in a depth-first way recursively. Besides knowing our current node, we just need to know if we're in 'reverse mode': a boolean to tell us whether to visit our node's children from left to right, or right to left.
Every time we go down a level in our tree, whether we're in 'reverse mode' or not is flipped.
Python code:
class TreeNode:
def __init__(self, parent=None):
self.parent = parent
self.children = []
def reverseParentheses(s: str) -> str:
root_node = TreeNode()
curr_node = root_node
# Build the tree
for let in s:
# Go down a level-- new child
if let == '(':
new_child = TreeNode(parent=curr_node)
curr_node.children.append(new_child)
curr_node = new_child
# Go back to our parent
elif let == ')':
curr_node = curr_node.parent
else:
curr_node.children.append(let)
answer = []
def dfs(node, is_reversed: bool):
nonlocal answer
num_children = len(node.children)
if is_reversed:
range_start, range_end, range_step = num_children-1, -1, -1
else:
range_start, range_end, range_step = 0, num_children, 1
for i in range(range_start, range_end, range_step):
if isinstance(node.children[i], str):
answer.append(node.children[i])
else:
dfs(node.children[i], not is_reversed)
dfs(root_node, False)
return ''.join(answer)
Here is the correct version for your callrecursion function:
def callrecursion(text):
print(text)
a = text.find('(') + 1
z = text.rfind(')') + 1
newStr = text[:a - 1] + text[a:z-1][::-1].replace('(', ']').replace(')', '[').replace(']', ')').replace('[', '(') + text[z:]
return newStr
You probably have to take into account if the parethesis is the first/last character.

Return a string from another string based off number and order of specific substrings

Suppose I have a string such as
s = "left-left-right-right-left"
and an empty string n = ''
and going from left to right for that string, read the number of lefts and rights that appear, and add an 'a' for every left and 'b' for every right that appears.
In other words a function like
def convert(s):
would return 'aabba'
I'm thinking along the lines of s.count, but the b's need to be between the a's, and count doesn't tell you where an occurrence of a substring happens.
The easiest way is to replace left by a and right by b. it should work
s = "left-left-right-right-left"
s = s.replace("left","a")
s=s.replace("right","b")
s=s.replace("-","")
Simplest solution.
def convert(s):
s = s.replace("left", "a")
s = s.replace("right", "b")
s = s.replace("-", "")
return s
OR
def convert(s):
return s.replace("left", "a").replace("right", "b").replace("-", "")
I've tried an recursive solution.
def rec_search(s, n):
if len(s) is 0:
return n
if s[-len('left'):] == 'left':
return rec_search(s[:-len('-left')], n) + 'a'
return rec_search(s[:-len('-right')], n) + 'b'
print rec_search('left-left-right-right-left', '')
This could also be done using a regular expression sub() as follows:
import re
s = "left-left-right-right-left"
print re.sub('left|right|-', lambda x: {'left':'a', 'right':'b', '-':''}[x.group(0)], s)
Giving you:
aabba
It works by replacing any left right or | with a function that looks up the replacement text in a dictionary.

Organizing strings in recursive functions - python

I'm trying to split and organize a string in a single function, my goal is to seperate lowercase and uppercase characters and then return a new string essentially like so:
"lowercasestring" + " " + "uppercasestring".
Importantly all characters must return in the order they were recieved but split up.
My problem is that i have to do this recursively in a single function(for educational purposes) and i struggle to understand how this is doable without an external function calling the recursive and then modifying the string.
def split_rec(string):
if string == '':
return "-" #used to seperate late
elif str.islower(string[0]) or string[0] == "_" or string[0] == ".": #case1
return string[0] + split_rec(string[1:])
elif str.isupper(string[0]) or string[0] == " " or string[0] == "|": #case2
return split_rec(string[1:]) + string[0]
else: #discard other
return split_rec(string[1:])
def call_split_rec(string):
##Essentially i want to integrate the functionality of this whole function into the recursion
mystring = split_rec(string)
left, right = mystring.split("-")
switch_right = right[::1]
print(left + " " + switchright)
The recursion alone would return:
"lowerUPPERcaseCASE" -> "lowercase" + "ESACREPPU"
My best attempt at solving this in a single function was to make case2:
elif str.isupper(string[-1]) or string[-1] == " " or string[-1] == "|": #case2
return split_rec(string[:-1]) + string[-1]
So that the uppercase letters would be added with last letter first, in order to correctly print the string. The issue here is that i obviously just get stuck when the first character is uppercase and the last one is lowercase.
I've spent alot of time trying to figure out a good solution to this, but im unable and there's no help for me to be found. I hope the question is not too stupid - if so feel free to remove it. Thanks!
I wouldn't do this recursively, but I guess you don't have a choice here. ;)
The simple way to do this in one function is to use a couple of extra arguments to act as temporary storage for the lower and upper case chars.
def split_rec(s, lo='', up=''):
''' Recursively split s into lower and upper case parts '''
# Handle the base case: s is the empty string
if not s:
return lo + ' ' + up
#Otherwise, append the leading char of s
# to the appropriate destination...
c = s[0]
if c.islower():
lo += c
else:
up += c
# ... and recurse
return split_rec(s[1:], lo, up)
# Test
print(split_rec("lowerUPPERcaseCASE"))
output
lowercase UPPERCASE
I have a couple of comments about your code.
It's not a great idea to use string as a variable name, since that's the name of a standard module. It won't hurt anything, unless you want to import that module, but it's still potentially confusing to people reading your code. The string module doesn't get a lot of use these days, but in the early versions of Python the standard string functions lived there. But then the str type inherited those functions as methods, making the old string functions obsolete.
And on that note, you generally should call those str methods as methods, rather than as functions. So don't do:
str.islower(s[0])
instead, do
s[0].islower()
Another take with recursive helper functions
def f(s):
def lower(s):
if not s:
return ''
c = s[0] if s[0].islower() else ''
return c + lower(s[1:])
def upper(s):
if not s:
return ''
c = s[0] if s[0].isupper() else ''
return c + upper(s[1:])
return lower(s) + ' ' + upper(s)
The easiest way would be to use sorted with a custom key:
>>> ''.join(sorted("lowerUPPERcaseCASE" + " ", key=str.isupper))
'lowercase UPPERCASE'
There's really no reason to use any recursive function here. If it's for educational purpose, you could try to find a problem for which it's actually a good idea to write a recursive function (fibonacci, tree parsing, merge sort, ...).
As mentioned by #PM2Ring in the comments, this sort works fine here because Python sorted is stable: when sorting by case, letters with the same case stay at the same place relative to one another.
Here is a way to do it with only the string as parameter:
def split_rec(s):
if not '|' in s:
s = s + '|'
if s.startswith('|'):
return s.replace('|', ' ')
elif s[0].islower():
return s[0] + split_rec(s[1:])
elif s[0].isupper():
# we move the uppercase first letter to the end
s = s[1:] + s[0]
return split_rec(s)
else:
return split_rec(s[1:])
split_rec('aAbBCD')
# 'ab ABCD'
The idea is:
We add a marker at the end (I chose |)
If the first char is lowercase, we return it + the organized rest
If it is uppercase, we move it to the end, and reorganize the whole string
We stop once we reach the marker: the current string is the marker followed by the organized uppercase letters. We replace the marker by a space and return it.

Python reversing a string using recursion

I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
n = n + 1
result = s[ start: n ] + " " + result
start = n
return result
But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much.
Any help would be appreciated.
def rreverse(s):
if s == "":
return s
else:
return rreverse(s[1:]) + s[0]
(Very few people do heavy recursive processing in Python, the language wasn't designed for it.)
To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself.
What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, right?
So the reverse of a string is the last character, followed by the reverse of everything but the last character, which is where the recursion comes in. The last character of a string can be written as x[-1] while everything but the last character is x[:-1].
Now, how do you "bottom out"? That is, what is the trivial case you can solve without recursion? One answer is the one-character string, which is the same forward and reversed. So if you get a one-character string, you are done.
But the empty string is even more trivial, and someone might actually pass that in to your function, so we should probably use that instead. A one-character string can, after all, also be broken down into the last character and everything but the last character; it's just that everything but the last character is the empty string. So if we handle the empty string by just returning it, we're set.
Put it all together and you get:
def backward(text):
if text == "":
return text
else:
return text[-1] + backward(text[:-1])
Or in one line:
backward = lambda t: t[-1] + backward(t[:-1]) if t else t
As others have pointed out, this is not the way you would usually do this in Python. An iterative solution is going to be faster, and using slicing to do it is going to be faster still.
Additionally, Python imposes a limit on stack size, and there's no tail call optimization, so a recursive solution would be limited to reversing strings of only about a thousand characters. You can increase Python's stack size, but there would still be a fixed limit, while other solutions can always handle a string of any length.
I just want to add some explanations based on Fred Foo's answer.
Let's say we have a string called 'abc', and we want to return its reverse which should be 'cba'.
def reverse(s):
if s == "":
return s
else:
return reverse(s[1:]) + s[0]
s = "abc"
print (reverse(s))
How this code works is that:
when we call the function
reverse('abc') #s = abc
=reverse('bc') + 'a' #s[1:] = bc s[0] = a
=reverse('c') + 'b' + 'a' #s[1:] = c s[0] = a
=reverse('') + 'c' + 'b' + 'a'
='cba'
If this isn't just a homework question and you're actually trying to reverse a string for some greater goal, just do s[::-1].
def reverse_string(s):
if s: return s[-1] + reverse_string(s[0:-1])
else: return s
or
def reverse_string(s):
return s[-1] + reverse_string(s[0:-1]) if s else s
I know it's too late to answer original question and there are multiple better ways which are answered here already. My answer is for documentation purpose in case someone is trying to implement tail recursion for string reversal.
def tail_rev(in_string,rev_string):
if in_string=='':
return rev_string
else:
rev_string+=in_string[-1]
return tail_rev(in_string[:-1],rev_string)
in_string=input("Enter String: ")
rev_string=tail_rev(in_string,'')
print(f"Reverse of {in_string} is {rev_string}")
s = input("Enter your string: ")
def rev(s):
if len(s) == 1:
print(s[0])
exit()
else:
#print the last char in string
#end="" prints all chars in string on same line
print(s[-1], end="")
"""Next line replaces whole string with same
string, but with 1 char less"""
return rev(s.replace(s, s[:-1]))
rev(s)
if you do not want to return response than you can use this solution. This question is part of LeetCode.
class Solution:
i = 0
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if self.i >= (len(s)//2):
return
s[self.i], s[len(s)-self.i-1] = s[len(s)-self.i-1], s[self.i]
self.i += 1
self.reverseString(s)

Categories

Resources