Професионална програма
Loading...
+ Нов въпрос
DilianaS avatar DilianaS 3 Точки

5. Balanced Brackets -> Python

Здравейте колеги,

имам затруднения с 5-та задача от допълнителните към темата Data Types and Variables. Ако може да ми дадете някоя насока в коя посока на мислене да тръгна?

Благодаря предварително, Диляна

 

 

1.   Balanced Brackets

You will receive n lines. On those lines, you will receive one of the following:

  • Opening bracket – “(“,
  • Closing bracket – “)” or
  • Random string

Your task is to find out if the brackets are balanced. That means after every closing bracket should follow an opening one. Nested parentheses are not valid, and if two consecutive opening brackets exist, the expression should be marked as unbalanced.

Input

  • On the first line, you will receive – the number of lines, which will follow
  • On the next lines, you will receive “(”, “)” or another string

Output

You have to print “BALANCED”, if the parentheses are balanced and “UNBALANCED” otherwise.

Constraints

  • will be in the interval [1…20]
  • The length of the stings will be between [1…100] characters

Examples

Input

Output

 

Input

Output

8

(

5 + 10

)

* 2 +

(

5

)

-12

BALANCED

 

6

12 *

)

10 + 2 -

(

5 + 10

)

 

UNBALANCED

 

0
Fundamentals Module
MartinBG avatar MartinBG 3827 Точки

Две примерни решения на проблема:

lines = int(input())

is_balanced = True
last_bracket = ''
for _ in range(0, lines):
    current = input()
    if current not in ['(', ')']:
        continue

    if last_bracket == '' and current == ')' or last_bracket == current:
        is_balanced = False
        break

    last_bracket = current

if is_balanced:
    print('BALANCED')
else:
    print('UNBALANCED')
lines = int(input())

is_balanced = True
has_open_bracket = False

for _ in range(0, lines):
    line = input()
    if line != '(' and line != ')':
        continue
        
    is_open_bracket = line == '('
    if has_open_bracket == is_open_bracket:
        is_balanced = False
        break
        
    has_open_bracket = is_open_bracket
    
if is_balanced:
    print('BALANCED')
else:
    print('UNBALANCED')

 

0
02/02/2021 21:29:47