2019๋ 10์ 27์ผ
๏ฟฝ
์ถ์ฒ: 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
๋ชจ๋์ด๋ผ๋๊ฑด ์ฒ์ ์์๋ค. ๋ฌธ์์ด์ด๋ ๋ฆฌ์คํธ๋ฅผ ์ํํ ๋ ์ฐ๊ธฐ ์ข์ ๊ฒ ๊ฐ๋ค.
- ์ํ ์ฃผ๊ธฐ ๋ฌธ์ ๋ ๊ธธ์ด๋ก ๋๋ ๋๋จธ์ง๋ฅผ ์ด์ฉํ์.