mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-31 06:33:44 +00:00
added algo for finding permutations of an array (#7614)
* Add files via upload * Delete permutations.cpython-310.pyc * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update permutations.py * Update permutations.py * Add files via upload * Delete permutations.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update permutations.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update permutations.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update permutations.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update data_structures/arrays/permutations.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update permutations.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update permutations.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update data_structures/arrays/permutations.py Co-authored-by: Chris O <46587501+ChrisO345@users.noreply.github.com> * Update permutations.py * Update permutations.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update permutations.py Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: Chris O <46587501+ChrisO345@users.noreply.github.com>
This commit is contained in:
parent
93ad7db97f
commit
efb4a3aee8
26
data_structures/arrays/permutations.py
Normal file
26
data_structures/arrays/permutations.py
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
def permute(nums: list[int]) -> list[list[int]]:
|
||||||
|
"""
|
||||||
|
Return all permutations.
|
||||||
|
|
||||||
|
>>> from itertools import permutations
|
||||||
|
>>> numbers= [1,2,3]
|
||||||
|
>>> all(list(nums) in permute(numbers) for nums in permutations(numbers))
|
||||||
|
True
|
||||||
|
"""
|
||||||
|
result = []
|
||||||
|
if len(nums) == 1:
|
||||||
|
return [nums.copy()]
|
||||||
|
for _ in range(len(nums)):
|
||||||
|
n = nums.pop(0)
|
||||||
|
permutations = permute(nums)
|
||||||
|
for perm in permutations:
|
||||||
|
perm.append(n)
|
||||||
|
result.extend(permutations)
|
||||||
|
nums.append(n)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import doctest
|
||||||
|
|
||||||
|
doctest.testmod()
|
Loading…
Reference in New Issue
Block a user