Skip to content

Latest commit

ย 

History

History
72 lines (51 loc) ยท 2.08 KB

2019-10-27-AT-numeric_formatter.md

File metadata and controls

72 lines (51 loc) ยท 2.08 KB

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

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

๏ฟฝ

์ถœ์ฒ˜: https://www.codewars.com/kata/generic-numeric-template-formatter/train/python

๋ฌธ์ œ

Your goal is to create a function to format a number given a template; if the number is not present, use the digits 1234567890 to fill in the spaces.

A few rules:

the template might consist of other numbers, special characters or the like: you need to replace only alphabetical characters (both lower- and uppercase); if the given or default string representing the number is shorter than the template, just repeat it to fill all the spaces. A few examples:

numeric_formatter("xxx xxxxx xx","5465253289") == "546 52532 89"
numeric_formatter("xxx xxxxx xx") == "123 45678 90"
numeric_formatter("+555 aaaa bbbb", "18031978") == "+555 1803 1978"
numeric_formatter("+555 aaaa bbbb") == "+555 1234 5678"
numeric_formatter("xxxx yyyy zzzz") == "1234 5678 9012"

์ ‘๊ทผ ๋ฐฉ๋ฒ•

  • template์„ ์ˆœํšŒํ•˜๋ฉด์„œ ์•ŒํŒŒ๋ฒณ์ธ ๋ถ€๋ถ„๋งŒ ์ˆซ์ž๋กœ ๋Œ€์ฒดํ•œ๋‹ค.

  • ์ˆซ์ž๋กœ ๋Œ€์ฒดํ•  ๋•Œ ์ฃผ์–ด์ง„ ์ˆซ์ž ๋ฐฐ์—ด์˜ ๊ธธ์ด๋กœ ์ธ๋ฑ์Šค๋ฅผ ๋‚˜๋ˆˆ ์ฃผ๊ธฐ๋ฅผ ์ด์šฉํ•œ๋‹ค.

  • ์ธ๋ฑ์Šค์—๋Š” template ์ค‘๊ฐ„์— ๊ณต๋ฐฑ์ด ํฌํ•จ๋˜๋ฉด ์•ˆ๋˜๋ฏ€๋กœ ์ƒˆ๋กœ ์ธ๋ฑ์Šค ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด ๊ณ„์‚ฐํ•œ๋‹ค.

๋‚ด ํ’€์ด

def numeric_formatter(template, data='1234567890'):
    answer = ''
    idx = 0
    for i in range(len(template)):
        if template[i].isalpha():
            answer += data[idx % len(data)]
            idx +=1
        else:
            answer += template[i]
    return answer

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

cycle ๋ชจ๋“ˆ ์ด์šฉ

def numeric_formatter(template, data='1234567890'):
    data = cycle(data)
    answer = []
    for c in template:
        if c.isalpha():
            answer.append(next(data))
        else:
            answer.append(c)
    return ''.join(answer)

๋ฐฐ์šด์ 

  • cycle ๋ชจ๋“ˆ์ด๋ผ๋Š”๊ฑด ์ฒ˜์Œ ์•Œ์•˜๋‹ค. ๋ฌธ์ž์—ด์ด๋‚˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœํšŒํ•  ๋•Œ ์“ฐ๊ธฐ ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค.

๋Š๋‚€์ 

  • ์ˆœํ™˜ ์ฃผ๊ธฐ ๋ฌธ์ œ๋Š” ๊ธธ์ด๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€๋ฅผ ์ด์šฉํ•˜์ž.