[Pythonの日常使用] itertools.permutationsの使用法

標準文法

itertools.permutations(iterable[, r])

意味

iterable内の要素の連続するr長の順列を返します。

rが指定されていないか、Noneの場合、rはデフォルトで反復可能の長さになり、可能なすべての完全長の順列が生成されます。

順列は辞書式順序で発行されます。したがって、入力反復可能オブジェクトがソートされている場合、順列タプルはソートされた順序で生成されます。

要素は、値ではなく、位置に基づいて一意として扱われます。したがって、入力要素が一意である場合、各順列に繰り返し値はありません。

簡単に言えば、イテレータ内の要素を返します連続長さ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