본문 바로가기

Python345

Flatten and sort an array Challenge: Given a two-dimensional array of integers, return the flattened version of the array with all the integers in the sorted (ascending) order. Example: Given [[3, 2, 1], [4, 6, 5], [], [9, 7, 8]], your function should return [1, 2, 3, 4, 5, 6, 7, 8, 9]. Solution: def flatten_and_sort(array): arr = [] for i in array: arr.extend(i) return sorted(arr) Other Solution: from itertools import c.. 2022. 8. 20.
Find the stray number You are given an odd-length array of integers, in which all of them are the same, except for one single number. Complete the method which accepts such an array, and returns that single different number. The input array will always be valid! (odd-length >= 3) Examples [1, 1, 2] ==> 2 [17, 17, 3, 17, 17, 17, 17] ==> 3 Solution: def stray(arr): import collections return [k for k, v in collections.C.. 2022. 8. 19.
Black _ Code Formatter 회피하는 방법 Black Code Formatter를 사용하는 이유는 일관된 코드 스타일을 유지함으로써 코드 가독성을 높이고 개발자들 간의 원활한 커뮤니케이션을 유도하기 위함이다. Python에서도 포맷팅 라이브러리가 있는데, 그중 Black은 대중적으로 많이 사용하는 Code Formatter 중에 하나이다. Code Formatter는 보통 '파일을 저장할 때'나 혹은 '커밋을 생성할 때' 등 자동 실행되도록 지정한다. 그런데 가끔은 Code Formatter 가 실행되지 않았으면 하는 때가 있다. 예를 들어 아래와 같은 dictionary가 있다고 가정해보자. 이를 포멧팅 하면 다음처럼 스타일이 수정된다. 포맷팅을 적용한 결과 코드라인이 13줄에서 58줄로 늘어났다... 이런 경우에는 포맷팅이 오히려 가독성을 떨.. 2022. 8. 19.
5 without numbers !! Write a function that always returns 5 Sounds easy right? Just bear in mind that you can't use any of the following characters: 0123456789*+-/ Good luck :) Solution: def unusual_five(): return int([i for i in str(ord("A"))].pop()) Other Solution: def unusual_five(): return len("five!") def unusual_five(): return ord("") 2022. 8. 19.
If you can't sleep, just count sheep!! If you can't sleep, just count sheep!! Task: Given a non-negative integer, 3 for example, return a string with a murmur: "1 sheep...2 sheep...3 sheep...". Input will always be valid, i.e. no negative integers. Solution: def count_sheep(n): return ''.join(f"{i} sheep..." for i in range(1, n+1)) 2022. 8. 17.
Python _ Protocol로 인터페이스 만드는 방법 Python에서 인터페이스를 구현하는 방법에는 여러 가지가 있지만 이번 글에서는 Protocol을 이용한 방법을 소개한다. 인터페이스란? 쉽게 말해 외부와 소통하기 위해 필요한 메서드를 정의한것이다. 하위 모듈들은 해당 인터페이스에 맞춰 기능을 구현한다. Protocol 사용법 아래 코드를 보자. from typing import Protocol class 감정(Protocol): def 기쁘다(self) -> str: ... def 슬프다(self) -> str: ... class 사람: def 기쁘다(self) -> str: return "기뻐!" def 화나다(self) -> str: return "화나!" class 사회생활: def 시작(self, 사람: 감정) -> None: self.사람 =.. 2022. 8. 16.