QQ个性网:专注于分享免费的QQ个性内容

关于我们| 网站公告| 广告服务| 联系我们| 网站地图

搜索
编程 JavaScript Java C++ Python SQL C Io ML COBOL Racket APL OCaml ABC Sed Bash Visual Basic Modula-2 Logo Delphi IDL Groovy Julia REXX Chapel X10 Forth Eiffel C# Go Rust PHP Swift Kotlin R Dart Perl Ruby TypeScript MATLAB Shell Lua Scala Objective-C F# Haskell Elixir Lisp Prolog Ada Fortran Erlang Scheme Smalltalk ABAP D ActionScript Tcl AWK IDL J PostScript IDL PL/SQL PowerShell

蓝因子 Python中内置的排列和组合方法

日期:2025/04/05 22:58来源:未知 人气:52

导读:Python提供了直接的方法来查找序列的排列和组合。这些方法在itertools包中。排列首先导入itertools包来实现python中的permutations方法。此方法接受一个列表作为输入,并返回一个包含列表形式的所有排列的元组的对象列表。from itertools import permutations# Get all permutations of [1, 2,......

Python提供了直接的方法来查找序列的排列和组合。这些方法在itertools包中。

排列

首先导入itertools包来实现python中的permutations方法。此方法接受一个列表作为输入,并返回一个包含列表形式的所有排列的元组的对象列表。

from itertools import permutations

Get all permutations of [1, 2, 3]

perm = permutations([1, 2, 3])

Print the obtained permutations

for i in list(perm):

print (i)

输出

(1, 2, 3)

(1, 3, 2)

(2, 1, 3)

(2, 3, 1)

(3, 1, 2)

(3, 2, 1)

如果想要得到长度为L的排列,那么就用这种方式实现它。

from itertools import permutations

Get all permutations of length 2

and length 2

perm = permutations([1, 2, 3], 2)

Print the obtained permutations

for i in list(perm):

print (i)

输出

(1, 2)

(1, 3)

(2, 1)

(2, 3)

(3, 1)

(3, 2)

这个程序的时间复杂度是O(n^r),其中n是输入数组的长度,r是要生成的排列的长度。 空间复杂度也是O(n^r),因为所有排列在打印之前都存储在内存中。

组合

该方法以一个列表和一个输入r作为输入,并返回一个元组的对象列表,该元组以列表形式包含长度r的所有可能组合。

from itertools import combinations

Get all combinations of [1, 2, 3]

and length 2

comb = combinations([1, 2, 3], 2)

Print the obtained combinations

for i in list(comb):

print (i)

输出

(1, 2)

(1, 3)

(2, 3)

1.组合以输入的字典排序顺序发出。因此,如果输入列表是排序的,则组合元组将以排序的顺序产生。

from itertools import combinations

Get all combinations of [1, 2, 3]

and length 2

comb = combinations([1, 2, 3], 2)

Print the obtained combinations

for i in list(comb):

print (i)

输出

(1, 2)

(1, 3)

(2, 3)

2.元素根据其位置而不是其值被视为唯一。因此,如果输入元素是唯一的,则在每个组合中将没有重复值。

from itertools import combinations

Get all combinations of [2, 1, 3]

and length 2

comb = combinations([2, 1, 3], 2)

Print the obtained combinations

for i in list(comb):

print (i)

输出

(2, 1)

(2, 3)

(1, 3)

3.如果我们想将相同的元素组合成一个元素,那么我们使用combinations_with_replacement。

from itertools import combinations_with_replacement

Get all combinations of [1, 2, 3] and length 2

comb = combinations_with_replacement([1, 2, 3], 2)

Print the obtained combinations

for i in list(comb):

print (i)

(1, 1)

(1, 2)

(1, 3)

(2, 2)

(2, 3)

(3, 3)

关于我们|网站公告|广告服务|联系我们| 网站地图

Copyright © 2002-2023 某某QQ个性网 版权所有 | 备案号:粤ICP备xxxxxxxx号

声明: 本站非腾讯QQ官方网站 所有软件和文章来自互联网 如有异议 请与本站联系 本站为非赢利性网站 不接受任何赞助和广告