함수 직접 만들어보기

Alex·2022년 3월 31일
0

아래 조건을 만족하는 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

-> 생각보다 쉽게 풀렸다. 그냥 리스트 처음요소랑 맨 마지막 요소 자리만 바꿔줌

profile
With Data or Without Data?

0개의 댓글