반응형
Quiz>
In a given list the first element should become the last one.
An empty list or list with only one element should stay the same.
example
Input:
List.
Output:
Iterable.
Example:
replace_first([1, 2, 3, 4]) == [2, 3, 4, 1]
replace_first([1]) == [1]
from typing import Iterable
def replace_first(items: list) -> Iterable:
# your code here
return items
if __name__ == '__main__':
print("Example:")
print(list(replace_first([1, 2, 3, 4])))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(replace_first([1, 2, 3, 4])) == [2, 3, 4, 1]
assert list(replace_first([1])) == [1]
assert list(replace_first([])) == []
print("Coding complete? Click 'Check' to earn cool rewards!")
Solve>
1. items 리스트의 길이가 0 이상이면
def replace_first(items: list) -> Iterable:
if len(items) > 0:
2. 첫 번째 원소를 가져올 리스트 생성
def replace_first(items: list) -> Iterable:
if len(items) > 0:
first_list = []
3. 첫 번째 원소를 for 문을 사용하여 가져옴
def replace_first(items: list) -> Iterable:
if len(items) > 0:
first_list = []
for i in items[:1]:
first_list.append(i)
4. 리스트의 2번째 원소부터 가져와서 맨 앞 원소가 뒤로 가야되므로 더하기로 구성
def replace_first(items: list) -> Iterable:
if len(items) > 0:
first_list = []
for i in items[:1]:
first_list.append(i)
return items[1:] + first_list
5. 빈 리스트일 경우 items를 그대로 반환
def replace_first(items: list) -> Iterable:
else:
return items
Code>
def replace_first(items: list) -> Iterable:
if len(items) > 0:
first_list = []
for i in items[:1]:
first_list.append(i)
return items[1:] + first_list
else:
return items
Example>
if __name__ == '__main__':
print("Example:")
print(list(replace_first([1, 2, 3, 4])))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(replace_first([1, 2, 3, 4])) == [2, 3, 4, 1]
assert list(replace_first([1])) == [1]
assert list(replace_first([])) == []
print("Coding complete? Click 'Check' to earn cool rewards!")
Result>
Example:
[2, 3, 4, 1]
Coding complete? Click 'Check' to earn cool rewards!
반응형
'Python_Matter > [Check_IO]Elementary' 카테고리의 다른 글
Split Pairs (0) | 2020.04.11 |
---|---|
Max Digit (0) | 2020.04.11 |
Remove All Before (0) | 2020.04.11 |
Backward String (0) | 2020.04.11 |
End Zeros (0) | 2020.04.11 |