mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-05 02:40:16 +00:00
421ace81ed
* [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.285 → v0.0.286](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.285...v0.0.286) - [github.com/tox-dev/pyproject-fmt: 0.13.1 → 1.1.0](https://github.com/tox-dev/pyproject-fmt/compare/0.13.1...1.1.0) * updating DIRECTORY.md * Fis ruff rules PIE808,PLR1714 --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
83 lines
2.1 KiB
Python
83 lines
2.1 KiB
Python
def multiplicative_persistence(num: int) -> int:
|
|
"""
|
|
Return the persistence of a given number.
|
|
|
|
https://en.wikipedia.org/wiki/Persistence_of_a_number
|
|
|
|
>>> multiplicative_persistence(217)
|
|
2
|
|
>>> multiplicative_persistence(-1)
|
|
Traceback (most recent call last):
|
|
...
|
|
ValueError: multiplicative_persistence() does not accept negative values
|
|
>>> multiplicative_persistence("long number")
|
|
Traceback (most recent call last):
|
|
...
|
|
ValueError: multiplicative_persistence() only accepts integral values
|
|
"""
|
|
|
|
if not isinstance(num, int):
|
|
raise ValueError("multiplicative_persistence() only accepts integral values")
|
|
if num < 0:
|
|
raise ValueError("multiplicative_persistence() does not accept negative values")
|
|
|
|
steps = 0
|
|
num_string = str(num)
|
|
|
|
while len(num_string) != 1:
|
|
numbers = [int(i) for i in num_string]
|
|
|
|
total = 1
|
|
for i in range(len(numbers)):
|
|
total *= numbers[i]
|
|
|
|
num_string = str(total)
|
|
|
|
steps += 1
|
|
return steps
|
|
|
|
|
|
def additive_persistence(num: int) -> int:
|
|
"""
|
|
Return the persistence of a given number.
|
|
|
|
https://en.wikipedia.org/wiki/Persistence_of_a_number
|
|
|
|
>>> additive_persistence(199)
|
|
3
|
|
>>> additive_persistence(-1)
|
|
Traceback (most recent call last):
|
|
...
|
|
ValueError: additive_persistence() does not accept negative values
|
|
>>> additive_persistence("long number")
|
|
Traceback (most recent call last):
|
|
...
|
|
ValueError: additive_persistence() only accepts integral values
|
|
"""
|
|
|
|
if not isinstance(num, int):
|
|
raise ValueError("additive_persistence() only accepts integral values")
|
|
if num < 0:
|
|
raise ValueError("additive_persistence() does not accept negative values")
|
|
|
|
steps = 0
|
|
num_string = str(num)
|
|
|
|
while len(num_string) != 1:
|
|
numbers = [int(i) for i in num_string]
|
|
|
|
total = 0
|
|
for i in range(len(numbers)):
|
|
total += numbers[i]
|
|
|
|
num_string = str(total)
|
|
|
|
steps += 1
|
|
return steps
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import doctest
|
|
|
|
doctest.testmod()
|