1 描述
給出4個正整數,使用加、減、乘、除4種運算以及括號把4個數連接起來得到一個結果等於24的表達式。
注:這裏加、減、乘、除以及括號的運算結果和運算優先級跟平常定義一致。
例如,對於5,5,5,1,可知 5× (5-1/5) = 24。又如,對於 1,1,4,2 無論如何都不能得到24
1.1 輸入格式
在代碼中的輸入部分輸入4個正整數。
1.2 輸出格式
對於每一組測試數據,如果可以得到24,輸出"YES"其算法;否則輸出“NO”。
2 大致思路
將四個數字進行全排列,在他們之間添加運算符號,最後將數字和操作符進行拼接運算。
運算符我們需要進行排列組合,因爲只有四個數字,所以只需要三個運算符,而且算法符可能會重複,比如三個都是+。
再遍歷四個數字的全排列,對每一組數字而言,遍歷所有組合的操作符。最後將數字和操作符進行拼接運算,就可以得到最終結果了。
3 知識點補充
1、首先我們對所有數字進行去全排列,這裏我們使用 itertools.permutations 來幫助我們完成。
iertools.permutations 用法演示
import itertools
a = int(input("請輸入第1個數字:"))
b = int(input("請輸入第2個數字:"))
c = int(input("請輸入第3個數字:"))
d = int(input("請輸入第4個數字:"))
my_list = [a, b, c, d]
result = [c for c in itertools.permutations(my_list, 4)]
for i, r in enumerate(result):
if i % 4 == 0:
print()
print(r, end="\t")
print("\n\n長度爲:", len(result))
運行結果:
請輸入第1個數字:1
請輸入第2個數字:2
請輸入第3個數字:3
請輸入第4個數字:4
(1, 2, 3, 4) (1, 2, 4, 3) (1, 3, 2, 4) (1, 3, 4, 2)
(1, 4, 2, 3) (1, 4, 3, 2) (2, 1, 3, 4) (2, 1, 4, 3)
(2, 3, 1, 4) (2, 3, 4, 1) (2, 4, 1, 3) (2, 4, 3, 1)
(3, 1, 2, 4) (3, 1, 4, 2) (3, 2, 1, 4) (3, 2, 4, 1)
(3, 4, 1, 2) (3, 4, 2, 1) (4, 1, 2, 3) (4, 1, 3, 2)
(4, 2, 1, 3) (4, 2, 3, 1) (4, 3, 1, 2) (4, 3, 2, 1)
長度爲: 24
4 具體代碼
from itertools import permutations
a = int(input("請輸入第1個數字:"))
b = int(input("請輸入第2個數字:"))
c = int(input("請輸入第3個數字:"))
d = int(input("請輸入第4個數字:"))
my_list = [a, b, c, d]
# 對4個整數隨機排列的列表
result = [c for c in permutations(my_list, 4)]
symbols = ["+", "-", "*", "/"]
list2 = [] # 算出24的排列組合的列表
flag = False
for one, two, three, four in result:
for s1 in symbols:
for s2 in symbols:
for s3 in symbols:
if s1 + s2 + s3 == "+++" or s1 + s2 + s3 == "***":
express = ["{0}{1}{2}{3}{4}{5}{6}".format(one, s1, two, s2, three, s3, four)] # 全加或者乘時,括號已經沒有意義。
else:
express = ["(({0}{1}{2}){3}{4}){5}{6}".format(one, s1, two, s2, three, s3, four),
"({0}{1}{2}){3}({4}{5}{6})".format(one, s1, two, s2, three, s3, four),
"(({0}{1}({2}{3}{4})){5}{6})".format(one, s1, two, s2, three, s3, four),
"{0}{1}(({2}{3}{4}){5}{6})".format(one, s1, two, s2, three, s3, four),
"{0}{1}({2}{3}({4}{5}{6}))".format(one, s1, two, s2, three, s3, four)]
for e in express:
try:
if eval(e) == 24:
list2.append(e)
flag = True
except ZeroDivisionError:
pass
list3 = set(list2) # 去除重複項
for c in list3:
print("YES:", c)
if not flag:
print("NO!")