redefined int_seq.factorial(); takes 4 times longer than math.factorial(), but is pure python and allows for sequences not starting with 1
This commit is contained in:
parent
3ac82ee526
commit
bfac2b9433
@ -1,12 +1,20 @@
|
|||||||
import math
|
def factorial(n: int, start: int = 1) -> int:
|
||||||
|
|
||||||
|
|
||||||
def factorial(n: int) -> int:
|
|
||||||
"""
|
"""
|
||||||
n! = 1 * 2 * 3 * 4 * ... * n
|
n! = 1 * 2 * 3 * 4 * ... * n
|
||||||
1, 1, 2, 6, 24, 120, 720, ...
|
1, 1, 2, 6, 24, 120, 720, ...
|
||||||
|
|
||||||
|
If you're looking for efficiency with start == 1, just use math.factorial(n)
|
||||||
|
which takes just 25% of the compute time on average, but this is the fastest
|
||||||
|
pure python implementation I could come up with and it allows for partial
|
||||||
|
multiplications, like 5 * 6 * 7 * 8 * .... * 17
|
||||||
"""
|
"""
|
||||||
return math.factorial(n)
|
if start == n:
|
||||||
|
return n
|
||||||
|
if n - start == 1:
|
||||||
|
return n * start
|
||||||
|
|
||||||
|
middle = start + (n - start) // 2
|
||||||
|
return factorial(middle, start) * factorial(n, middle + 1)
|
||||||
|
|
||||||
|
|
||||||
def fibonacci(n: int) -> int:
|
def fibonacci(n: int) -> int:
|
||||||
|
|||||||
@ -20,7 +20,9 @@ class StopWatch:
|
|||||||
self.stopped = perf_counter_ns()
|
self.stopped = perf_counter_ns()
|
||||||
self.total_elapsed += self.elapsed()
|
self.total_elapsed += self.elapsed()
|
||||||
|
|
||||||
reset = start
|
def reset(self):
|
||||||
|
self.total_elapsed = 0
|
||||||
|
self.start()
|
||||||
|
|
||||||
def elapsed(self) -> int:
|
def elapsed(self) -> int:
|
||||||
if self.stopped is None:
|
if self.stopped is None:
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user