TheAlgorithms-Python

Форк
0
/
persistence.py 
82 строки · 2.1 Кб
1
def multiplicative_persistence(num: int) -> int:
2
    """
3
    Return the persistence of a given number.
4

5
    https://en.wikipedia.org/wiki/Persistence_of_a_number
6

7
    >>> multiplicative_persistence(217)
8
    2
9
    >>> multiplicative_persistence(-1)
10
    Traceback (most recent call last):
11
        ...
12
    ValueError: multiplicative_persistence() does not accept negative values
13
    >>> multiplicative_persistence("long number")
14
    Traceback (most recent call last):
15
        ...
16
    ValueError: multiplicative_persistence() only accepts integral values
17
    """
18

19
    if not isinstance(num, int):
20
        raise ValueError("multiplicative_persistence() only accepts integral values")
21
    if num < 0:
22
        raise ValueError("multiplicative_persistence() does not accept negative values")
23

24
    steps = 0
25
    num_string = str(num)
26

27
    while len(num_string) != 1:
28
        numbers = [int(i) for i in num_string]
29

30
        total = 1
31
        for i in range(len(numbers)):
32
            total *= numbers[i]
33

34
        num_string = str(total)
35

36
        steps += 1
37
    return steps
38

39

40
def 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

79
if __name__ == "__main__":
80
    import doctest
81

82
    doctest.testmod()
83

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.