Skip to content

Latest commit

ย 

History

History
80 lines (56 loc) ยท 1.91 KB

2019-11-03-AT-persistence.md

File metadata and controls

80 lines (56 loc) ยท 1.91 KB

2019๋…„ 10์›” 27์ผ

codewars - Generic numeric template formatter {docsify-ignore-all}

๏ฟฝ

์ถœ์ฒ˜: https://www.codewars.com/kata/55bf01e5a717a0d57e0000ec/solutions/python

๋ฌธ์ œ

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:

persistence(39) => 3  # Because 3*9 = 27, 2*7 = 14, 1*4=4
                       # and 4 has only one digit.

persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126,
                       # 1*2*6 = 12, and finally 1*2 = 2.

persistence(4) => 0   # Because 4 is already a one-digit number
persistence(39) # returns 3, because 3*9=27, 2*7=14, 1*4=4
                 # and 4 has only one digit

persistence(999) # returns 4, because 9*9*9=729, 7*2*9=126,
                  # 1*2*6=12, and finally 1*2=2

persistence(4) # returns 0, because 4 is already a one-digit number

์ ‘๊ทผ ๋ฐฉ๋ฒ•

  • ๊ฐ ์ž๋ฆฌ์ˆ˜์˜ ๊ณฑ์„ ๊ตฌํ•œ๋‹ค.

    • ๊ฐ ์ž๋ฆฌ์ˆ˜๋ฅผ ๊ณฑํ•  ๋•Œ๋งˆ๋‹ค count +1์„ ํ•œ๋‹ค.
  • ์ž๋ฆฌ์ˆ˜๊ฐ€ ํ•œ ์ž๋ฆฌ๊ฐ€ ๋  ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•œ๋‹ค.

๋‚ด ํ’€์ด

# ๊ฐ ์ž๋ฆฌ์ˆ˜์˜ ๊ณฑ์„ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜
def mul(n):
    num = 1
    for i in range(len(n)):
        num *= int(n[i])
    return str(num)


def persistence(n):
    n = str(n)
    count = 0
    while len(n) > 1:
        n = mul(n)
        count += 1
    return count

๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด

operator.mul, functools.reduce ๋ชจ๋“ˆ ์ด์šฉ

import operator
from functools import reduce
def persistence(n):
    i = 0
    while n>=10:
        n= reduce(operator.mul,[int(x) for x in str(n)],1)
        i+=1
    return i

๋ฐฐ์šด์ 

  • operator ๋ชจ๋“ˆ์—๋Š” ์›ฌ๋งŒํ•œ ์—ฐ์‚ฐ์ž ํ•จ์ˆ˜๊ฐ€ ๋‹ค ๊ตฌํ˜„๋˜์–ด ์žˆ๋‹ค.
  • reduce: ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ reduce์™€ ๊ฐ™๋‹ค. reduce๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ฝ”๋“œ์˜ ์–‘์„ ๋งŽ์ด ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.