[Python3] 프로그래머스 둘만의 암호(index(), find(), replace())

민갱·2023년 6월 19일

CT

목록 보기
12/35

뭔가 알파벳 전부를 담아놓고 처리해야할것같다는 느낌만 받았고 반복문 으로 풀면 될것같다는 느낌으로 접근🫡
테스트 케이스만 통과하고 이후에 한개도 성공하지 못하고 런타임에러,,,ㅎㅎ

둘만의 암호

실패

def solution(s, skip, index):
    alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    list1 = list(s)
    list3 = []
    answer = ''
    for i in s:
        cnt = 0
        for j in range(index):
            if alpha[alpha.index(i)+j] in skip:
                cnt+=1
        list3.append(cnt+index)
    for i in range(len(list3)):
        a = alpha.index(list1[i]) + list3[i]
        if a >= 26:
            a -=26
        answer+=alpha[a]  
    return answer

성공

def solution(s, skip, index):
    answer = ''
    alpha = "abcdefghijklmnopqrstuvwxyz"
    
    for i in skip:
        if i in alpha:
            alpha = alpha.replace(i,'')

    for j in s:
        change = alpha[(alpha.index(j)+index) % len(alpha)]
        answer+=change
    
    return answer

기본적인 개념은 비슷하게 접근했지만 다른부분들이 있다.

  • 알파벳을 먼저 문자열로 선언
  • skip에 들어있는 문자들을 공백으로 변경
  • alpha.index(알파벳)+index의 수가 알파벳 갯수 26보다 넘어갈 경우 다시 a로 부터 세어주어야 할때의 나머지 당연하지만 놓친 개념
    • 7 % 26 = 7
    • 28 % 26 = 2

find() & replace()

  • 첫번째 위치 반환
# 문자 'x'가 첫번째 위치한 자리를 출력
>>> 'oxoxoxoxox'.find('x'))  # find 함수
1 
>>> 'oxoxoxoxox'.index('x'))  # index 함수
1

# 문자 'o'가 첫번째 위치한 자리를 출력
>>> a = 'hello'
>>> a.find('o'))  # find 함수
4
>>> a.index('o'))  # index 함수
4
  • 요소가 없을 경우
    • find()는 요소가 없으면 -1을 반환한다.
    • index()는 요소가 없으면 에러를 반환한다.
    • try & catch를 사용하던, 분기 처리가 필요하다.
# 문자가 없을 때
>>> a = 'hello'

>>> a.find('z)
-1

>>> a.index('z)
Traceback (most recent call last):
  File "C:/project/steel/python/a.py", line 4, in <module>
    a.find('z)
ValueError: substring not found

>>> a = 'hello'

>>> try:
>>>    print(a.index('z'))
>>> except ValueError:
>>>    print(-1)
  • 시작, 종료 위치 지정
# 문자열중 2번째 위치부터 처음 'x'가 위치한 자리
>>> 'oxoxoxoxox'.index('x', 2)
3

# a변수에서 1번째~3번째 사이에 문자 'o'가 위치한 자리
>>> a = 'hello'
>>> a.find('o', 1, 3)
-1	
# find함수는 찾는 값이 없을 때 -1을 출력한다.
  • 값을 계속 호출하고 싶을 경우
    • find()는 loop을 돌면서 계속 반환하지만
    • index()는 except가 필요
a = 'oxoxoxoxox'

index = 0
while index > -1:
    index = a.find('x', index)
    if index > -1:
        print(index)
        index += len('x')

# 1 3 ...


index = 0
while index > -1:
	try:
	    index = a.find('x', index)
        index += len('x')
    except ValueError:
    	break
profile
가보자고

0개의 댓글