-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTweedledeesSplitBrackets.py
89 lines (76 loc) · 2.39 KB
/
TweedledeesSplitBrackets.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# a simple parser for python. use get_number() and get_word() to read
def parser():
while 1:
data = list(input().split(' '))
for number in data:
if len(number) > 0:
yield(number)
input_parser = parser()
def get_word():
global input_parser
return next(input_parser)
def get_number():
data = get_word()
try:
return int(data)
except ValueError:
return float(data)
def checkPossibility():
# not enough close brackets for the open brackets
if (bracketInv["("] != bracketInv[")"]) or (bracketInv["["] != bracketInv["]"]):
print ("impossible")
sys.exit(0)
bracketCount = sum(bracketInv.values())
# can't split into even sets
if bracketCount % 4 != 0:
print ("impossible")
sys.exit(0)
# numpy and scipy are available for use
#import numpy
#import scipy
import sys
data = sys.stdin.readline().strip('\n').strip('\r')
bracketInv = {}
for char in "()[]":
bracketInv[char] = data.count(char)
# first cursory check if valid sequence can be formed
checkPossibility()
encountered = { "(" : 0, ")" : 0, "[" : 0, "]" : 0 }
hanging = {"(" : 0, "[" : 0}
inS1 = { "(" : 0, ")" : 0, "[" : 0, "]" : 0 }
hangingS1 = {"(" : 0, "[" : 0}
inS2 = { "(" : 0, ")" : 0, "[" : 0, "]" : 0 }
hangingS2 = {"(" : 0, "[" : 0}
sequence = []
def checkHangings(bracket, openB):
if hanging[openB] == 0:
print("impossible")
sys.exit(0)
else:
if hangingS1[openB] == 0: # no need to close bracket in s1
hangingS2[openB] -= 1
hanging[openB] -= 1
sequence.append("2")
else: # hanging brackets in S1, append to S1
hangingS1[openB] -= 1
hanging[openB] -= 1
sequence.append("1")
for bracket in data:
if bracket == ")":
openB = "("
checkHangings(bracket, openB)
elif bracket == "]":
openB = "["
checkHangings(bracket, openB)
else:
s1HangCount = sum(hangingS1.values())
s2HangCount = sum(hangingS2.values())
if s1HangCount > s2HangCount: # more hanging brackets in s1
hangingS2[bracket] += 1
hanging[bracket] += 1
sequence.append("2")
else: # less in s1, it can accomodate more
hangingS1[bracket] += 1
hanging[bracket] += 1
sequence.append("1")
print(' '.join(sequence))