import
itertools
import
operator
import
tkinter as tk
from
tkinter
import
messagebox
def
find_24(nums):
if
len
(nums) !
=
4
:
raise
ValueError(
"必须输入4个数"
)
ops
=
[operator.add, operator.sub, operator.mul, operator.truediv]
op_symbols
=
[
'+'
,
'-'
,
'*'
,
'/'
]
for
num_permutation
in
itertools.permutations(nums):
for
ops_permutation
in
itertools.product(ops, repeat
=
3
):
for
op_symbols_permutation
in
itertools.product(op_symbols, repeat
=
3
):
expressions
=
[
f
"(({num_permutation[0]} {op_symbols_permutation[0]} {num_permutation[1]}) {op_symbols_permutation[1]} {num_permutation[2]}) {op_symbols_permutation[2]} {num_permutation[3]}"
,
f
"({num_permutation[0]} {op_symbols_permutation[0]} ({num_permutation[1]} {op_symbols_permutation[1]} {num_permutation[2]})) {op_symbols_permutation[2]} {num_permutation[3]}"
,
f
"({num_permutation[0]} {op_symbols_permutation[0]} {num_permutation[1]}) {op_symbols_permutation[1]} ({num_permutation[2]} {op_symbols_permutation[2]} {num_permutation[3]})"
,
f
"{num_permutation[0]} {op_symbols_permutation[0]} (({num_permutation[1]} {op_symbols_permutation[1]} {num_permutation[2]}) {op_symbols_permutation[2]} {num_permutation[3]})"
,
f
"{num_permutation[0]} {op_symbols_permutation[0]} ({num_permutation[1]} {op_symbols_permutation[1]} ({num_permutation[2]} {op_symbols_permutation[2]} {num_permutation[3]}))"
]
for
expr
in
expressions:
try
:
if
abs
(
eval
(expr)
-
24
) <
1e
-
6
:
return
expr
except
ZeroDivisionError:
continue
return
"没有找到能计算出24的方式"
def
calculate(event
=
None
):
try
:
input_str
=
entry.get()
numbers
=
list
(
map
(
int
, input_str.split()))
if
len
(numbers) !
=
4
or
any
(n <
1
or
n >
10
for
n
in
numbers)
or
len
(
set
(numbers)) !
=
4
:
raise
ValueError
result
=
find_24(numbers)
result_label.config(text
=
result)
history_listbox.insert(tk.END, f
"{input_str} -> {result}"
)
except
ValueError:
messagebox.showerror(
"输入错误"
,
"输入无效,请输入1-10中的4个不同数字。"
)
root
=
tk.Tk()
root.title(
"24点计算器"
)
instruction_label
=
tk.Label(root, text
=
"请输入1-10中的4个不同数字,用空格分隔:"
)
instruction_label.pack()
entry
=
tk.Entry(root)
entry.pack()
entry.bind(
"<Return>"
, calculate)
calculate_button
=
tk.Button(root, text
=
"计算"
, command
=
calculate)
calculate_button.pack()
result_label
=
tk.Label(root, text
=
"")
result_label.pack()
history_label
=
tk.Label(root, text
=
"历史记录:"
)
history_label.pack()
history_listbox
=
tk.Listbox(root, width
=
50
, height
=
10
)
history_listbox.pack()
root.mainloop()