MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / additive_persistence

Function additive_persistence

maths/persistence.py:40–76  ·  view source on GitHub ↗

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 value

(num: int)

Source from the content-addressed store, hash-verified

38
39
40def additive_persistence(num: int) -> int:
41 """
42 Return the persistence of a given number.
43
44 https://en.wikipedia.org/wiki/Persistence_of_a_number
45
46 >>> additive_persistence(199)
47 3
48 >>> additive_persistence(-1)
49 Traceback (most recent call last):
50 ...
51 ValueError: additive_persistence() does not accept negative values
52 >>> additive_persistence("long number")
53 Traceback (most recent call last):
54 ...
55 ValueError: additive_persistence() only accepts integral values
56 """
57
58 if not isinstance(num, int):
59 raise ValueError("additive_persistence() only accepts integral values")
60 if num < 0:
61 raise ValueError("additive_persistence() does not accept negative values")
62
63 steps = 0
64 num_string = str(num)
65
66 while len(num_string) != 1:
67 numbers = [int(i) for i in num_string]
68
69 total = 0
70 for i in range(len(numbers)):
71 total += numbers[i]
72
73 num_string = str(total)
74
75 steps += 1
76 return steps
77
78
79if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected