学校网站建设市场广东东莞疫情最新情况
# 请在此处编写代码
# 24点游戏
import itertools# 计算24点游戏代码
def twentyfour(cards):"""(1)itertools.permutations(可迭代对象):通俗地讲,就是返回可迭代对象的所有数学全排列方式。itertools.permutations("1118") -> 即将数字1118进行全排列组合(2)itertools.product(*iterables, repeat=1)iterables是可迭代对象,repeat指定iterable重复几次返回一个或者多个iterables中的元素的笛卡尔积的元组即为product(list1, list2) 依次取出list1中的每1个元素,与list2中的每1个元素,组成元组,repeat即为元组中有几个元素,最多重复几次(3)"""for num in itertools.permutations(cards):#提取数字for ops in itertools.product("+-*/", repeat=3):#提取运算符# ({0}{4}{1}){5}({2}{6}{3}) - > 即在{0}{1}{2}{3}放上数字,{4}{5}{6}放上运算符号,只能放三个,四个数字中间只能放三个运算符# 带括号有8种方法#带括号的意思是三个运算符的优先运算组成方式有8类# 1. (ab)cdbsd1 = '({0}{4}{1}){5}{2}{6}{3}'.format(*num, *ops)# 2. a(bc)dbsd2 = '{0}{4}({1}{5}{2}){6}{3}'.format(*num, *ops)# 3. ab(cd)bsd3 = '{0}{4}{1}{5}({2}{6}{3})'.format(*num, *ops)# 4. (ab)(cd)bsd4 = '({0}{4}{1}){5}({2}{6}{3})'.format(*num, *ops)# 5. ((ab)c)dbsd5 = '(({0}{4}{1}){5}{2}){6}{3}'.format(*num, *ops)# 6. (a(bc))dbsd6 = '({0}{4}({1}{5}{2})){6}{3}'.format(*num, *ops)# 7. a((bc)d)bsd7 = '{0}{4}(({1}{5}{2}){6}{3})'.format(*num, *ops)# 8. a(b(cd))bsd8 = '{0}{4}({1}{5}({2}{6}{3}))'.format(*num, *ops)# print([bsd1, bsd2, bsd3, bsd4, bsd5, bsd6, bsd7, bsd8])for bds in [bsd1, bsd2, bsd3, bsd4, bsd5, bsd6, bsd7, bsd8]:try:if abs(eval(bds) - 24.0) < 1e-20:return "24点结果 = "+bdsexcept ZeroDivisionError: # 零除错误continuereturn "Not fond"cards = ['2484', '1126', '1127', '1128', '2484', '1111']
for card in cards:print(twentyfour(card))
总结:
1、了解了枚举算法注意事项
在列举的过程中,既不能遗漏也不要重复。
2、明晰了枚举算法的核心
itertools.permutations将输入的可迭代对象即四个数字进行所有可能的全排列;
for num in itertools.permutations(cards):#提取数字并排列
itertools.product将设定好的List1即四个运算符中提取三个与repeat=3相对应;
for ops in itertools.product("+-*/", repeat=3):#提取运算符
将提取的数字排列与运算符依次放入八种可能的优先运算方式中,如果可以满足24点游戏的规则那么输出结果,如果8种运算方式都无法成功得出结果那么就返回”not fond“。
3、学习了4个数字三个运算符的优先排列方式
共有八种:
(ab)cd、a(bc)d、ab(cd)、(ab)(cd)、((ab)c)d、(a(bc))d、a((bc)d)、a(b(cd))。
4、运算结果
输入数字 | 2484 | 1126 | 1127 | 1128 | 2484 | 1111 |
运算结果 | (2+4)*(8-4) | ((1+1)+2)*6 | (1+2)*(1+7) | (1+(1*2))*8 | (2+4)*(8-4) | not fond |