# 枚举思想-24点游戏

## 24点游戏

规则：4个数字的运算结果等于24；

```python
import itertools,random

def twentyfour(card):
    # itertools.permutations(card) ： 对card对4个数字进行全排列，穷举所有组合
    for nums in itertools.permutations(card):
        # itertools.product：对+-*/符合进行笛卡尔积组合，3个一对
        for ops in itertools.product('+-*/',repeat=3):
            # 这里只构造3中形式的计算式，其它形式可能得不到24，或者可化成和下面的一致，总之，枚举尽可能所有可能得到解的情况
            # *nums：0，1，2，3；*ops：4，5，6
            bds1='({0}{4}{1}){5}({2}{6}{3})'.format(*nums,*ops) #(a+b)*(c-d)
            bds2='(({0}{4}{1}){5}{2}){6}{3}'.format(*nums,*ops) #(a+b)*c-d
            bds3='{0}{4}({1}{5}({2}{6}{3}))'.format(*nums,*ops) #a/(b-(c/d)
            for bds in [bds1,bds2,bds3]:
                try:
                    if abs(eval(bds)-24.0)<1e-10:
                        return 1,bds
                except ZeroDivisionError:#除数是0的错误
                    continue
    return 0,card

cards=[i+1 for i in range(10)]
print(cards)

for _ in range(10):#随机抽10次
    card=random.sample(cards, 4) #从cards中抽4张数字
    succ,out=twentyfour(card)
    if succ ==0:
        print('%s 不能计算到 24'%out)
    else:
        print('%s =24'%out)
```

```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(5+9)+(10*1) =24
((10-8)*9)+6 =24
6*(5-(9-8)) =24
(7+9)*(6/4) =24
(3*10)-(6*1) =24
(7*5)-(1+10) =24
8*(6-(10-7)) =24
((10-9)+2)*8 =24
(9+8)+(3+4) =24
(4+9)+(1+10) =24
```

## itertools

是python的迭代器模块，itertools提供的工具相当高效且节省内存。

```python
# permutations 全排列
for item in itertools.permutations(['a', 'b', 'c']):
    print(item)
print('-'*50)

for item in itertools.permutations(['a', 'b', 'c'],2):
    print(item)
print('-'*50)

# itertools.product 笛卡尔积的元组
for item in itertools.product([1,2,3],[100,200]):
    print(item)

print('-'*50)
# product(A, repeat=4) means the same as product(A, A, A, A).
# for ops in itertools.product('+-*/','+-*/','+-*/',):
for ops in itertools.product('+-*/',repeat=3):
    print(ops)

for i in itertools.count(10): #从10开始无限循环
    print(i)
    break

for i in itertools.islice(itertools.count(10), 5): #从10开始，输出5个元素后结束
    print(i)

for item in itertools.cycle('XYZ'):#X,Y,Z轮流输出，无限循环
    print(item)
    break

import operator
# accumulate 迭代器将返回累计求和结果
print(list(itertools.accumulate(range(1,10)))) #默认，累加
print(list(itertools.accumulate(range(1,10),operator.mul))) #operator.mul：累乘
print(list(itertools.accumulate(range(1,10),operator.add))) #operator.add：累加
```

## random随机操作

```python
import random
values = [1, 2, 3, 4, 5, 6]

print(random.choice(values))

print(random.sample(values, 4))

print(values)
random.shuffle(values)
print(values)
```

```
4
[2, 3, 1, 5]
[1, 2, 3, 4, 5, 6]
[2, 4, 5, 3, 6, 1]
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/shua-ti/si-xiang-lei/mei-ju/24dian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
