Skip to content

Commit ca818c6

Browse files
committed
quxes code
1 parent 058cad6 commit ca818c6

1 file changed

Lines changed: 94 additions & 0 deletions

File tree

‎basic/quxes_fb.py‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
# !/usr/bin/env python3
2+
3+
# author: greyshell
4+
5+
"""
6+
On a mysterious island there are creatures known as Quxes which come in three colors: red, green, and blue. One power
7+
of the Qux is that if two of them are standing next to each other, they can transform into a single creature of the
8+
third color.
9+
10+
Given N Quxes standing in a line, determine the smallest number of them remaining after any possible sequence of such
11+
transformations.
12+
13+
For example, given the input ['R', 'G', 'B', 'G', 'B'], it is possible to end up with a single Qux through the
14+
following steps:
15+
16+
Arrangement | Change
17+
----------------------------------------
18+
['R', 'G', 'B', 'G', 'B'] | (R, G) -> B
19+
['B', 'B', 'G', 'B'] | (B, G) -> R
20+
['B', 'R', 'B'] | (R, B) -> G
21+
['B', 'G'] | (B, G) -> R
22+
['R']
23+
"""
24+
25+
d = list()
26+
27+
count = 0
28+
29+
30+
def transform(a, b):
31+
s = 82 + 71 + 66
32+
color = dict()
33+
color[82] = 'R'
34+
color[71] = 'G'
35+
color[66] = 'B'
36+
c = s - (ord(a) + ord(b))
37+
return color[c]
38+
39+
40+
def backtrack(i, j):
41+
global count
42+
if len(d) == j:
43+
print(d)
44+
exit(0)
45+
elif d[i] != d[j]:
46+
a1 = d.pop(i)
47+
a2 = d.pop(i)
48+
c = transform(a1, a2)
49+
d.insert(i, c)
50+
count += 1
51+
return i
52+
elif d[i] == d[j]:
53+
k = backtrack(i + 1, j + 1)
54+
a1 = d.pop(k - 1)
55+
a2 = d.pop(k - 1)
56+
c = transform(a1, a2)
57+
d.insert(k - 1, c)
58+
count += 1
59+
return k - 1
60+
61+
62+
def solution(quexes):
63+
"""
64+
time complexity: O(n)
65+
space complexity: O(n) for the storing the
66+
:param quexes:
67+
:return:
68+
"""
69+
global count
70+
for ch in quexes:
71+
d.append(ch)
72+
73+
n = len(d)
74+
75+
while count < n:
76+
if d[0] == d[1]:
77+
backtrack(0, 1)
78+
else:
79+
c = transform(d.pop(1), d.pop(0))
80+
d.insert(0, c)
81+
count += 1
82+
83+
return d
84+
85+
86+
def main():
87+
quxes = ['R', 'G', 'B', 'B', 'B', 'R']
88+
print(quxes)
89+
result = solution(quxes)
90+
print(f"{result}")
91+
92+
93+
if __name__ == '__main__':
94+
main()

0 commit comments

Comments
 (0)