From 357f981e5d45d474d5160bbd1401f416a1188e09 Mon Sep 17 00:00:00 2001 From: Knox-7744 <119045829+Knox-7744@users.noreply.github.com> Date: Tue, 31 Oct 2023 22:53:21 +0530 Subject: [PATCH] Create rstring.py --- rstring.py | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 rstring.py diff --git a/rstring.py b/rstring.py new file mode 100644 index 00000000..04ebb18a --- /dev/null +++ b/rstring.py @@ -0,0 +1,56 @@ +# Function to create an empty stack. It +# initializes size of stack as 0 +def createStack(): + stack = [] + return stack + +# Function to determine the size of the stack +def size(stack): + return len(stack) + +# Stack is empty if the size is 0 +def isEmpty(stack): + if size(stack) == 0: + return true + +# Function to add an item to stack . It +# increases size by 1 +def push(stack, item): + stack.append(item) + +# Function to remove an item from stack. +# It decreases size by 1 +def pop(stack): + if isEmpty(stack): + return + return stack.pop() + +# A stack based function to reverse a string +def reverse(string): + n = len(string) + + # Create a empty stack + stack = createStack() + + # Push all characters of string to stack + for i in range(0, n, 1): + push(stack, string[i]) + + # Making the string empty since all + # characters are saved in stack + string = "" + + # Pop all characters of string and put + # them back to string + for i in range(0, n, 1): + string += pop(stack) + + return string + + +# Driver code +s = "string" +print("The original string is : ", end="") +print(s) +print("The reversed string(using stack) is : ", end="") +print(reverse(s))