[Algorithm] ๐Ÿšฉ[programmers] ์ˆซ์ž ๋ฌธ์ž์—ด๊ณผ ์˜๋‹จ์–ด (Feat. replace ํ•จ์ˆ˜, strip ํ•จ์ˆ˜)

myeonjiยท2022๋…„ 2์›” 5์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
32/89
post-custom-banner

> replace ํ•จ์ˆ˜

๋ฌธ์ž์—ด์„ ๋ณ€๊ฒฝํ•˜๋Š” ํ•จ์ˆ˜๋กœ, ๋ฌธ์ž์—ด ์•ˆ์—์„œ ํŠน์ • ๋ฌธ์ž๋ฅผ ์ƒˆ๋กœ์šด ๋ฌธ์ž๋กœ ๋ณ€๊ฒฝํ•˜๋Š” ๊ธฐ๋Šฅ

  • ๋ฌธ์ž์—ด.replace(old, new, [count]) ํ˜•์‹์œผ๋กœ ์‚ฌ์šฉ
    • old : ํ˜„์žฌ ๋ฌธ์ž์—ด์—์„œ ๋ณ€๊ฒฝํ•  ๋ฌธ์ž
    • new : old์™€ ๋ฐ”๊ฟ€ ์ƒˆ๋กœ์šด ๋ฌธ์ž
    • count : ๋ณ€๊ฒฝํ•  ํšŸ์ˆ˜, ์ž…๋ ฅํ•˜์ง€ ์•Š์œผ๋ฉด old์˜ ๋ฌธ์ž์—ด ์ „์ฒด ๋ณ€๊ฒฝ(๊ธฐ๋ณธ๊ฐ’์€ ์ „์ฒด๋ฅผ ์˜๋ฏธํ•˜๋Š” count = -1)

> strip ํ•จ์ˆ˜

๋ฌธ์ž์—ด ์‹œ์ž‘๊ณผ ๋ฌธ์ž์—ด ๋์—์„œ ํŠน์ • ๋ฌธ์ž๋ฅผ ์ œ๊ฑฐ

  • strip([chars]) : ์ธ์ž๋กœ ์ „๋‹ฌ๋œ ๋ฌธ์ž๋ฅผ String์˜ ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ์—์„œ ์ œ๊ฑฐ
  • lstrip([chars]) : ์ธ์ž๋กœ ์ „๋‹ฌ๋œ ๋ฌธ์ž๋ฅผ String์˜ ์™ผ์ชฝ์—์„œ ์ œ๊ฑฐ
  • rstrip([chars]) : ์ธ์ž๋กœ ์ „๋‹ฌ๋œ ๋ฌธ์ž๋ฅผ String์˜ ์˜ค๋ฅธ์ชฝ์—์„œ ์ œ๊ฑฐ
  • ์ธ์ž๋ฅผ ์ „๋‹ฌํ•˜์ง€ ์•Š์œผ๋ฉด String์—์„œ ๊ณต๋ฐฑ์„ ์ œ๊ฑฐ

์–ด..์–ด๋ ต๋‹ค.. ๋ฌธ์ œ๋งŒ ๋ณด๊ณ  ์‰ฌ์šธ ์ค„..
๊ทธ๋ž˜๋„ ํ’€์—ˆ๋‹ค.. ํšจ์œจ์ ์ธ ์ฝ”๋“œ๋Š” ์ ˆ๋Œ€ ์•„๋‹ˆ๋‹ผใ…‹ใ…‹ใ…‹ ๋ถ€๋„๋Ÿฝ๋‹ค ใ… ใ…  ;;;;
replace ํ•จ์ˆ˜๋ฅผ ์ƒ๊ฐํ•ด๋‚ด๋Š”๊ฒŒ ์•„์ด๋””์–ด์˜€๋˜ ๊ฒƒ ๊ฐ™๋‹ค.

< ๋‚ด ๋‹ต์•ˆ >

def solution(s):
    d = [['0', 'zero'], ['1', 'one'], ['2', 'two'], ['3', 'three'], ['4', 'four'], ['5', 'five'], ['6', 'six'],
         ['7', 'seven'], ['8', 'eight'], ['9', 'nine']]
    s = list(s)
    answer = ''
    ss = []
    for i in range(len(s)):
        for j in range(len(d)):
            if s[i] == d[j][0]:
                for k in range(len(d[j][1])):
                    ss.append(d[j][1][k])
                break
        else:
            ss.append(s[i])

    a = ''
    for j in range(len(ss)):
        a = a + ss[j]
        for k in range(len(d)):
            if a == d[k][1]:
                answer = answer + d[k][0]
                a = ''

    return int(answer)

๋‚œ ์ด๋ ‡๊ฒŒ ๊ธธ์—ˆ๋Š”๋ฐ..
๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด ๋ณด๊ณ  ํ˜„ํƒ€์™”๋‹ค ๐Ÿ˜‡

๋‚˜๋„ ์ฒ˜์Œ์— ์‚ฌ์ „์œผ๋กœ ๋‘๊ณ  ํ’€์—ˆ๋Š”๋ฐ ๋„ˆ๋ฌด ๋ณต์žกํ•˜๊ฒŒ ์ƒ๊ฐํ–ˆ๋Š”์ง€ ๋ง‰ํ˜€์„œ ์ค‘๊ฐ„์— ๋ฆฌ์ŠคํŠธ๋กœ ๋ฐ”๊ฟจ๋Š”๋ฐ.. ์ด๋ ‡๊ฒŒ๋„ ๋˜๊ตฌ๋‚˜..

num_dic = {"zero":"0", "one":"1", "two":"2", "three":"3", "four":"4", "five":"5", "six":"6", "seven":"7", "eight":"8", "nine":"9"}

def solution(s):
    answer = s
    for key, value in num_dic.items():
        answer = answer.replace(key, value)
    return int(answer)

๋˜๋Š”

def solution(s):
    words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']

    for i in range(len(words)):
        s = s.replace(words[i], str(i))

    return int(s)
profile
DBA, ๊ฒฝ์ œ ๊ทธ๋ฆฌ๊ณ  ๊ณ ๋ƒฅ์ด
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€