-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchallenge_balanced_symbols_my_solution.py
60 lines (49 loc) · 1.51 KB
/
challenge_balanced_symbols_my_solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!usr/bin/env python3
from data_structures.stack import Stack
# In this challenge, your prompt is to create a function that takes in a
# string of symbol pairs as a parameter.
# The function should return true if the symbol string is balanced or
# false if it isn't.
# In order for symbols to be balanced, each opening symbol should also have
# a closing symbol. And the symbols must be properly nested.
# You should make use of a stack in your solution.
# Example of balanced symbols: ([{}]) ([]{}()) ((()))
# Example of unbalanced symbols: (([{]) [}([){]
allowed_symbols = {'(': ')',
'[': ']',
'{': '}'}
def is_balanced(symbols):
"""
>>> is_balanced('([{}])')
True
>>> is_balanced('([]{}())')
True
>>> is_balanced('((()))')
True
>>> is_balanced('(([{])')
False
>>> is_balanced('[}([){]')
False
>>> is_balanced('[')
False
"""
if not isinstance(symbols, str):
raise TypeError('symbols must be a string')
if len(symbols) == 0:
raise ValueError('symbols must have at least one symbol')
stack = Stack()
for symbol in symbols:
if stack.is_empty():
stack.push(symbol)
else:
top_symbol = stack.peek()
if allowed_symbols.get(top_symbol, None) == symbol:
stack.pop()
else:
stack.push(symbol)
if stack.is_empty():
return True
return False
if __name__ == "__main__":
import doctest
doctest.testmod()