Python - Adding And Changing Elements To Lists

ryan·2020년 8월 21일
0

Assignment
주어진 2개의 리스트를 하나의 리스트로 합친 후 리스트의 첫 element와 마지막 element를 서로 바꿔준 후 리스트 전체를 출력해주세요.

예를 들어, 다음과 같은 2개의 리스트가 주어졌다면

list1 = [1, 2, 3, 4, 5]
list2 = [6, 7]

출력되야 하는 결과물은 다음과 같습니다,

[7, 2, 3, 4, 5, 6, 1]

두개 다 빈 리스트가 들어온다면 빈리스트를 반환해야 합니다.

처음에 Assignment를 풀 때, 두 리스트를 더해주고, list1의 index[-1]과 list2의 index[0]을 두 리스트가 더해진 리스트(result)에 update시켜주면 된다고 생각해서 아래와 같이 코드를 작성했는데 오류가 났다.

TRY

def merge_and_swap(list1, list2):
  # 이 함수를 구현해 주세요
  result = list1 + list2
  result[0] = list2[-1]
  result[-1] = list1[0]
  return result
  
  if list1 == [] or list2 == []:
    return list1 + list2
  else:
    result[0] = list2[-1]
    result[-1] = list1[0]
    return result
    
    Traceback (most recent call last):
  File "/home/runner/unit_tests.py", line 16, in test_testName
    self.assertEquals(merge_and_swap([], []), [])
  File "/home/runner/unit_tests.py", line 6, in merge_and_swap
    result[0] = list2[-1]
IndexError: list index out of range

리스트가 만약에 빈 리스트라면, 빈 리스트를 반환해야하는데

list1 = []
list2 = []

print(list1[-1])
IndexError: list index out of range

print(list2[0])
IndexError: list index out of range

빈 리스트의 인덱스는 존재하지않기때문에 오류가 발생하게된다.

그래서 if 문으로 리스트가 빈 리스트일 때, result(list1+list2)를 업데이트해주기 전에, 두 빈 리스트를 더해서 빈 리스트를 리턴하게 만들었고, 다음 코드를 작성하였다.

My Solution

def merge_and_swap(list1, list2):
  # 이 함수를 구현해 주세요
  result = list1 + list2
  if list1 == [] or list2 == []:
    return list1 + list2
  else:
    result[0] = list2[-1]
    result[-1] = list1[0]
    return result

언제나 그렇지만, 모범 답안을 보면 새롭다. 모범 답안에서는 리스트의 길이에 따라서 리스트의 길이가 1보다 컸을 때, 즉 두 리스트 중에 빈 리스트가 없을 때를 if문으로 코드를 작성해서 리스트의 첫 번째 요소와 마지막 요소를 업데이트해주었다.

Model Solution

def merge_and_swap(list1, list2):
  list1 = list1 + list2
  
  length = len(list1)
  
  if length > 1:
    first             = list1[0]
    last              = list1[length - 1]
    list1[0]          = last
    list1[length - 1] = first

    return list1
  else:
    return list1

마지막 요소를 인덱스로 구할 때, 이렇게 쓰자.

list1[-1] ## 보다

list1[length - 1]	## 이렇게 쓰도록 해보자
profile
👨🏻‍💻☕️ 🎹🎵 🐰🎶 🛫📷

0개의 댓글