Skip to content

Commit 4e0f2cc

Browse files
authored
Update 20231213_01.md
1 parent 215dd2b commit 4e0f2cc

File tree

1 file changed

+86
-1
lines changed

1 file changed

+86
-1
lines changed

202312/20231213_01.md

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,92 @@ postgres=# select solve_24_game(1,6,7,12);
132132
12+7-1+6
133133
12+7+6-1
134134
(18 rows)
135-
```
135+
```
136+
137+
补充支持括号的函数:
138+
```
139+
postgres=# CREATE OR REPLACE FUNCTION solve_24_game(num1 INTEGER, num2 INTEGER, num3 INTEGER, num4 INTEGER)
140+
RETURNS SETOF TEXT AS $$
141+
import itertools
142+
143+
def solve_24_game(num1, num2, num3, num4):
144+
nums = [num1, num2, num3, num4]
145+
operators = ['+', '-', '*', '/']
146+
perms = itertools.permutations(nums)
147+
for perm in perms:
148+
for ops in itertools.product(operators, repeat=3):
149+
expression = "(({0}{4}{1}){5}{2}){6}{3}".format(*perm, *ops)
150+
try:
151+
result = eval(expression)
152+
if result == 24:
153+
yield expression
154+
except ZeroDivisionError:
155+
continue
156+
157+
return
158+
159+
return solve_24_game(num1, num2, num3, num4)
160+
$$ LANGUAGE plpython3u;
161+
CREATE FUNCTION
162+
postgres=# select (1,2,3,4);
163+
row
164+
-----------
165+
(1,2,3,4)
166+
(1 row)
167+
168+
postgres=# select solve_24_game(1,2,3,4);
169+
solve_24_game
170+
---------------
171+
((1+2)+3)*4
172+
((1*2)*3)*4
173+
((1*2)*4)*3
174+
((1+3)+2)*4
175+
((1*3)*2)*4
176+
((1*3)*4)*2
177+
((1*4)*2)*3
178+
((1*4)*3)*2
179+
((2+1)+3)*4
180+
((2*1)*3)*4
181+
((2/1)*3)*4
182+
((2*1)*4)*3
183+
((2/1)*4)*3
184+
((2+3)+1)*4
185+
((2*3)*1)*4
186+
((2*3)/1)*4
187+
((2*3)*4)*1
188+
((2*3)*4)/1
189+
((2*4)*1)*3
190+
((2*4)/1)*3
191+
((2*4)*3)*1
192+
((2*4)*3)/1
193+
((3+1)+2)*4
194+
((3*1)*2)*4
195+
((3/1)*2)*4
196+
((3*1)*4)*2
197+
((3/1)*4)*2
198+
((3+2)+1)*4
199+
((3*2)*1)*4
200+
((3*2)/1)*4
201+
((3*2)*4)*1
202+
((3*2)*4)/1
203+
((3*4)*1)*2
204+
((3*4)/1)*2
205+
((3*4)*2)*1
206+
((3*4)*2)/1
207+
((4*1)*2)*3
208+
((4/1)*2)*3
209+
((4*1)*3)*2
210+
((4/1)*3)*2
211+
((4*2)*1)*3
212+
((4*2)/1)*3
213+
((4*2)*3)*1
214+
((4*2)*3)/1
215+
((4*3)*1)*2
216+
((4*3)/1)*2
217+
((4*3)*2)*1
218+
((4*3)*2)/1
219+
(48 rows)
220+
```
136221

137222
后面又有拿Oracle SQL来战的林春老师, 以及那CTE语法来战的陈刚老师, 可距离德哥给出plpython函数已经半小时过去了, 好了游戏结束.
138223

0 commit comments

Comments
 (0)