TheAlgorithms-Python
82 строки · 2.1 Кб
1def multiplicative_persistence(num: int) -> int:2"""3Return the persistence of a given number.
4
5https://en.wikipedia.org/wiki/Persistence_of_a_number
6
7>>> multiplicative_persistence(217)
82
9>>> multiplicative_persistence(-1)
10Traceback (most recent call last):
11...
12ValueError: multiplicative_persistence() does not accept negative values
13>>> multiplicative_persistence("long number")
14Traceback (most recent call last):
15...
16ValueError: multiplicative_persistence() only accepts integral values
17"""
18
19if not isinstance(num, int):20raise ValueError("multiplicative_persistence() only accepts integral values")21if num < 0:22raise ValueError("multiplicative_persistence() does not accept negative values")23
24steps = 025num_string = str(num)26
27while len(num_string) != 1:28numbers = [int(i) for i in num_string]29
30total = 131for i in range(len(numbers)):32total *= numbers[i]33
34num_string = str(total)35
36steps += 137return steps38
39
40def additive_persistence(num: int) -> int:41"""42Return the persistence of a given number.
43
44https://en.wikipedia.org/wiki/Persistence_of_a_number
45
46>>> additive_persistence(199)
473
48>>> additive_persistence(-1)
49Traceback (most recent call last):
50...
51ValueError: additive_persistence() does not accept negative values
52>>> additive_persistence("long number")
53Traceback (most recent call last):
54...
55ValueError: additive_persistence() only accepts integral values
56"""
57
58if not isinstance(num, int):59raise ValueError("additive_persistence() only accepts integral values")60if num < 0:61raise ValueError("additive_persistence() does not accept negative values")62
63steps = 064num_string = str(num)65
66while len(num_string) != 1:67numbers = [int(i) for i in num_string]68
69total = 070for i in range(len(numbers)):71total += numbers[i]72
73num_string = str(total)74
75steps += 176return steps77
78
79if __name__ == "__main__":80import doctest81
82doctest.testmod()83