Skip to content

Commit 84e7972

Browse files
coderbeta1pre-commit-ci[bot]cclauss
authored
Added Derangements Calculator (#9927)
* Added Derangement calculator * Updated derangement.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Updated derangement.py * updating DIRECTORY.md * Apply suggestion from @cclauss --------- 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: cclauss <cclauss@users.noreply.github.com>
1 parent 71bd79a commit 84e7972

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

DIRECTORY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -726,6 +726,7 @@
726726
* [Continued Fraction](maths/continued_fraction.py)
727727
* [Decimal Isolate](maths/decimal_isolate.py)
728728
* [Decimal To Fraction](maths/decimal_to_fraction.py)
729+
* [Derangement](maths/derangement.py)
729730
* [Dodecahedron](maths/dodecahedron.py)
730731
* [Double Factorial](maths/double_factorial.py)
731732
* [Dual Number Automatic Differentiation](maths/dual_number_automatic_differentiation.py)
@@ -876,6 +877,7 @@
876877
* [Two Pointer](maths/two_pointer.py)
877878
* [Two Sum](maths/two_sum.py)
878879
* [Volume](maths/volume.py)
880+
* [Weighted Average](maths/weighted_average.py)
879881
* [Zellers Congruence](maths/zellers_congruence.py)
880882

881883
## [Matrix](matrix)

maths/derangement.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
A Python implementation for finding number of
3+
derangements possible for k objects
4+
https://en.wikipedia.org/wiki/Derangement
5+
"""
6+
7+
8+
def derangement(objects: int) -> int:
9+
"""
10+
Calculates the number of derangements of k objects.
11+
:param objects:the number of objects ( -1 < objects < 1560 )
12+
:return :the number of derangements
13+
:raises :ValueError: If objects is negative.
14+
15+
Examples:
16+
>>> derangement(3)
17+
2
18+
>>> derangement(5)
19+
44
20+
>>> derangement(10)
21+
1334961
22+
"""
23+
if objects < 0:
24+
raise ValueError("k must be a non-negative integer. Retry")
25+
26+
# Base cases
27+
if objects in (0, 1):
28+
return 0
29+
30+
# Initialize the derangement counts
31+
derange_1 = 1
32+
derange_2 = 0
33+
answer = 1
34+
35+
# Calculate derangements using dynamic programming
36+
# Answer: F(n) = (n - 1) * ( F(n - 1) + F(n - 2) )
37+
for i in range(3, objects + 1):
38+
answer = (i - 1) * (derange_1 + derange_2)
39+
derange_2 = derange_1
40+
derange_1 = answer
41+
42+
return answer

0 commit comments

Comments
 (0)