함수 직접 만들어보기
아래 조건을 만족하는 merge_and_swap 함수를 완성
- 2개의 리스트를 input으로 받습니다.
- input 받은 2개의 리스트를 하나의 리스트로 합칩니다.
- 합쳐진 리스트의 첫 element와 마지막 element를 서로 바꾼 후 리스트 전체를 리턴 합니다.
- input 모두 빈 리스트이면 빈 리스트를 리턴합니다.
Try 1.
def merge_and_swap(list1, list2):
if len(list1) == 0 and len(list2) == 0:
return []
else:
list1 = list1 + list2
last = list1.pop()
my_list = []
my_list = [last] + list1[1:] + [list1[0]]
return my_list
line 8, in merge_and_swap
my_list = [last] + list1[1:] + [list1[0]]
IndexError: list index out of range
-> .......???????
-> list 범위 밖에 있는 인덱스를 가져오려고 해서 나오는 에러...
Try 2.
def merge_and_swap(list1, list2):
if list1 == [] and list2 == []:
return []
else:
list1 = list1 + list2
list1[0], list1[len(list1)-1] = list1[len(list1)-1], list1[0]
return list1
-> 생각보다 쉽게 풀렸다. 그냥 리스트 처음요소랑 맨 마지막 요소 자리만 바꿔줌
Author And Source
이 문제에 관하여(함수 직접 만들어보기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@alexms0316/함수-직접-만들어보기저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)