Skip to content

Commit efb4a3a

Browse files
rajansh87pre-commit-ci[bot]cclaussChrisO345
authored
added algo for finding permutations of an array (TheAlgorithms#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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> Co-authored-by: Chris O <[email protected]>
1 parent 93ad7db commit efb4a3a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
def permute(nums: list[int]) -> list[list[int]]:
2+
"""
3+
Return all permutations.
4+
5+
>>> from itertools import permutations
6+
>>> numbers= [1,2,3]
7+
>>> all(list(nums) in permute(numbers) for nums in permutations(numbers))
8+
True
9+
"""
10+
result = []
11+
if len(nums) == 1:
12+
return [nums.copy()]
13+
for _ in range(len(nums)):
14+
n = nums.pop(0)
15+
permutations = permute(nums)
16+
for perm in permutations:
17+
perm.append(n)
18+
result.extend(permutations)
19+
nums.append(n)
20+
return result
21+
22+
23+
if __name__ == "__main__":
24+
import doctest
25+
26+
doctest.testmod()

0 commit comments

Comments
 (0)