코드로 우주평화

Persistent Bugger 본문

나는 이렇게 학습한다/Algorithm & SQL

Persistent Bugger

daco2020 2022. 3. 20. 18:34
반응형

Description:

Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.

For example (Input --> Output):

39 --> 3 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit)
999 --> 4 (because 9*9*9 = 729, 7*2*9 = 126, 1*2*6 = 12, and finally 1*2 = 2)
4 --> 0 (because 4 is already a one-digit number)

 

 

Solution:

1. Separate and multiply by the number of digits.
2. Repeat until the multiplied value is a single digit.
3. Count the number of repetitions for each repetition.
4. Returns the last iteration count.

 

 

import math

def persistence(n):
    def prod(n, count=1):
        n = math.prod([int(i) for i in str(n)])
        if n < 10:
            return count
        count += 1
        return prod(n, count)
    return 0 if n < 10 else prod(n)

A recursive function was used.
math.prod() is a method that multiplies array elements.

 

 

 

반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

Dashatize it  (0) 2022.03.22
Data Reverse  (0) 2022.03.21
자료구조 _ Hash table  (0) 2022.03.20
자료구조 _ Queue 그리고 Stack  (0) 2022.03.20
Multiplication table  (0) 2022.03.19