Last active
October 21, 2021 04:46
-
-
Save changx03/da010c0097933ca95a2bbad5e2da9a4e to your computer and use it in GitHub Desktop.
Stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Predefined methods | |
class Stack: | |
def __init__(self): | |
self.__items = [] | |
def is_empty(self): | |
return self.__items == [] | |
def push(self, item): | |
self.__items.append(item) | |
def pop(self): | |
if self.is_empty(): | |
raise IndexError('ERROR: The stack is empty!') | |
return self.__items.pop() | |
def peek(self): | |
if self.is_empty(): | |
raise IndexError('ERROR: The stack is empty!') | |
return self.__items[len(self.__items) - 1] | |
def size(self): | |
return len(self.__items) | |
def __str__(self): | |
return 'Stack: ' + str(self.__items) | |
def contains_digit(my_str): | |
for c in my_str: | |
if c.isdigit(): | |
return True | |
return False | |
def decompress(comp_str): | |
if comp_str == '' or not contains_digit(comp_str): | |
return comp_str | |
else: | |
repeats = Stack() | |
for i in range(len(comp_str)): | |
if comp_str[i].isdigit(): | |
if repeats.size() == 0 or repeats.peek()[0] != int(comp_str[i]): | |
repeats.push((int(comp_str[i]), i)) | |
elif repeats.peek()[0] == int(comp_str[i]): | |
n, start = repeats.pop() | |
return decompress(comp_str[:start] + comp_str[start+1: i] * n + comp_str[i+1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment