Last active
March 20, 2023 11:54
-
-
Save Abdur-rahmaanJ/9e45a5609721a44bb6b3666826841313 to your computer and use it in GitHub Desktop.
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
def identify_symbols(string): | |
elements = [] | |
num_stack = [] # holds numbers | |
index = 0 | |
while index < len(string): | |
char = string[index] | |
if char in '+-/*()': | |
# Add number to elements | |
if num_stack: | |
elements.append(''.join(num_stack)) | |
num_stack = [] | |
if (char in '+-/*'): | |
if (char == '*' and string[index+1] == '*'): | |
elements.append('**') | |
index += 1 | |
else: | |
elements.append(char) | |
elif char == '(': | |
elements.append('(') | |
elif char == ')': | |
elements.append(')') | |
elif char in '0123456789': | |
num_stack.append(char) | |
index += 1 | |
# If numbers remain on the stack | |
if num_stack: | |
elements.append(''.join(num_stack)) | |
num_stack = [] | |
return elements | |
print(identify_symbols('111+2+(33**2)-1*1')) | |
# ['111', '+', '2', '+', '(', '33', '**', '2', ')', '-', '1', '*', '1'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment