【python日用】itertools.permutations用法

标准语法

itertools.permutations(iterable[, r])

含义

Return successive r length permutations of elements in the iterable.

If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.

Permutations are emitted in lexicographic sort order. So, if the input iterable is sorted, the permutation tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each permutation.

简单来说呢就是返回迭代器中元素的连续长度为r的排列。也就是全排列呗。
如果r未指定或为None,则r默认为可迭代对象的长度,并生成所有可能的全长度排列。

代码

def permutations(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = range(n)
    cycles = range(n, n-r, -1)
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

仔细看这个代码,相信各位能看明白的哈。

算法示例

此处我们可以来看一下24点游戏的代码咯

# -*- coding: utf-8 -*-
"""
Created on Wed Jan 20 23:29:53 2021

@author: Administrator
"""
import itertools
def twentyfour(cards):
    for nums in itertools.permutations(cards):
        for ops in itertools.product('+-*/',repeat=3):
            #构造三种中缀表达式 bsd
            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 bds
                except ZeroDivisionError: #除零错误
                    continue
                
    return 'Not fount'

cards = [1,2,3,4]
for card in cards:
    print(twentyfour(card))

猜你喜欢

转载自blog.csdn.net/weixin_51656605/article/details/112913422