프로그래머스 연습문제 - 영어 끝말잇기 (level2)
def solution(n, words):
head = []
tail = []
for idx, word in enumerate(words):
if word in words[:idx]: return [idx % n +1, idx // n + 1]
head.append([idx,word[0]])
tail.append([idx,word[-1]])
try:
for i in range(len(words)):
if(head[i+1][1] != tail[i][1] ) :
return [head[i+1][0]%n + 1,head[i+1][0]//n +1]
except IndexError:
return [0,0]
try - except를 매번 문제를 풀 때마다 여기에 써볼 수 있을까 저기에 써볼 수 있을까 끼워맞춰 봤었는데 오늘 이 문제에서 try - except를 사용해봤다!
군더더기가 많아서 아쉽다.
def solution(n, words):
for p, word in enumerate(words):
last = word[-1]
if p+1 < len(words):
first = words[p+1][0]
# 중복된 단어가 있다면
if word in words[:p]: return [(p%n)+1, p//n+1]
# 이어쓰기 X
elif last != first: return [(p+1)%n+1, (p+1)//n+1]
else:
# 마지막 원소가 중복된 값인지 체크
if word in words[:p]: return [(p%n)+1, p//n+1]
else:
return [0,0]
4줄짜리 솔루션도 있지만 그건 이해하기도 어렵고, 이 솔루션이 내게는 더 베스트인 것 같다.
list = ['apple', 'melon', 'grape', 'kiwi']
if 'apple' in list:
print(True)
# print: True
list = ['apple', 'melon', 'grape', 'kiwi']
if 'Apple' not in list:
print(True)
# print: True
# enumerate(iterable, start=0)
directions = ["north", "east", "south", "west"]
list(enumerate(directions))
# [(0, 'north'), (1, 'east'), (2, 'south'), (3, 'west')]
for index, value in enumerate(directions):
print("{}: {}".format(index, value))
# [(0, 'north'), (1, 'east'), (2, 'south'), (3, 'west')]
t = [1, 5, 7, 33, 39, 52]
for p in enumerate(t):
... print(p)
...
(0, 1)
(1, 5)
(2, 7)
(3, 33)
(4, 39)
(5, 52)
찾는 문자가 없는 경우에 -1을 출력한다.
문자열을 찾을 수 있는 변수는 문자열만 사용이 가능하다.
리스트, 튜플, 딕셔너리 자료형에서는 find 함수를 사용할 수 없다.
AttributeError 에러 발생.
찾는 문자가 없는 경우에 ValueError 에러가 발생한다.
문자열, 리스트, 튜플 자료형에서 사용 가능
딕셔너리 자료형에는 사용할 수 없어 AttributeError 에러가 발생한다.
a = 'hello'
a.find('o')) # find 함수 : 4
a.index('o')) # index 함수 :4
# a변수에서 1번째~3번째 사이에 문자 'o'가 위치한 자리
a = 'hello'
a.find('o', 1, 3) # -1
y = [10, 20, 30]
try:
index, x = map(int, input('인덱스와 나눌 숫자를 입력하세요: ').split())
print(y[index] / x)
# as 뒤에 변수를 지정하면 에러를 받아옴
except ZeroDivisionError as e:
# e에 저장된 에러 메시지 출력
print('숫자를 0으로 나눌 수 없습니다.', e)
except IndexError as e:
print('잘못된 인덱스입니다.', e)