Python/Grammar
-
[Python 2차원 리스트] 리스트 반복과 리스트 컴프리헨션의 차이Python/Grammar 2024. 3. 12. 13:55
알고리즘 문제를 풀면서 '리스트 반복'과 '리스트 컴프리헨션'이 각각 어떻게 1차원 리스트로부터 2차원 리스트를 'copy'하는지 그 차이를 알게되었다.리스트 반복2차원 리스트 생성 방법: [[0] * m] * n1차원 리스트 '[[0] * m]' 를 'n'번 반복해서 2차원 리스트를 생성할 때 shallow copy를 수행함. 즉, 모든 행이 동일한 리스트 객체를 참조하게 되므로 한 행의 데이터를 변경하면 모든 행에 그 변경점이 반영됨. 리스트 컴프리헨션2차원 리스트 생성 방법: [[0] * m for _ in range(n)]'n'번만큼 for 문으로 '[0] * m'의 결과를 새로 생성하는 과정을 반복해서 2차원 리스트를 생성함. 각 반복마다 독립적인 리스트가 생성되기 때문에 deep copy의..
-
회문 판별과 N-gram 만들기Python/Grammar 2023. 3. 25. 20:55
# 1. 회문 판별하기 회문(palindrome)이란? 거꾸로 읽어도 제대로 읽은 것과 같은 단어나 문장을 말한다. 예를 들어 SOS, level, nurses run, rotator, 기러기, 토마토 등이 있다. 1-1. 반복문으로 문자 검사하기 0부터 문자열 길이의 절반만큼 반복하면서 왼쪽 문자, 왼쪽 문자와 대칭되는 위치의 오른쪽 문자를 비교해서 문자가 다르면 회문이 아니라고 판단한다.word = intput()is_palindrome = Truefor i in range(len(word) // 2): if word[i] != word[-i -1]: is_palindrome = False breakprint(is_palindrome) 1-2. 시퀀스 뒤집기로 문자 검..
-
15. 제너레이터 사용하기Python/Grammar 2023. 3. 11. 11:00
💡 제너레이터(generator)란? 이터레이터를 생성해주는 함수로 "발생자"라고 부르기도 한다. 함수 안에서 yield 키워드를 사용함으로써 제너레이터로 동작하는 함수를 만들 수 있다. 제너레이터 객체는 __iter__, __next__ 메소드를 가지고 있으며, 제너레이터 객체에서 __next__ 메소드를 호출할 때마다 함수 안의 마지막 yield까지 코드를 실행하며 yield에서 값을 발생(generate)시킨다. 따라서 이름을 제너레이터라고 한다. 정리해보면 이터레이터를 만드는 방법은 다음 네 가지가 있다. 1. iterable.__iter__() 2. __iter__, __next__ 메소드를 구현한 클래스의 객체 생성 3. __getitem__ 메소드를 구현한 클래스의 객체 생성 4. yield..
-
12. elif를 사용하여 여러 방향으로 분기하기Python/Grammar 2023. 3. 10. 22:14
# 1. elif 사용하기 elif는 "else if"라는 뜻으로 if 조건식이 참이 아닌 상태에서 조건식을 지정할 때 사용한다. elif 여러 개를 사용해 다수 개의 조건을 지정할 수 있으며 적용 예시로는 자판기가 있다. if, else와 같이 조건식 끝에 콜론을 붙이고 다음줄은 들여쓰기를 해야 한다. 단독으로는 사용할 수 없어 if-elif 형태로 사용하거나 if-elif-else 형태로 사용한다. else와 함께 사용할 때는 반드시 elif가 else보다 먼저 와야한다. else는 선행된 모든 조건을 만족하지 않는 조건을 가지기 때문이다. 1-1. if, elif, else 모두 사용하기 모든 상황을 처리하기 위해 if-elif / if-else 형태의 두 가지 분기로는 부족할 때 if-elif-e..
-
11. else를 사용하여 두 방향으로 분기하기Python/Grammar 2023. 3. 9. 23:23
# 1. else 사용하기 1-1. if와 else의 기본 형태와 실행 흐름 알아보기 else의 코드는 if 조건식을 만족하지 않을 때 실행한다. 즉, if 조건식이 True이면 if 본문(if의 코드)이 실행되고 False이면 else 본문(else의 코드)이 실행된다. else 조건문은 단독으로 사용할 수 없으며, 조건식 뒤에 콜론을 붙이는 형식과 실행할 코드를 조건식 다음줄에 들여쓰기 후 작성하는 규칙은 if 조건문과 같다. ❗️ False로 취급하는 것들 - None - False - 0인 숫자들 -> 0, 0.0, 0j - 비어있는 문자열 -> '', "" - 비어있는 리스트 -> [] - 비어있는 튜플 -> () - 비어있는 딕셔너리 -> {} - 비어있는 세트 -> set() - 클래스 인스..
-
13. 반복문 제어하기Python/Grammar 2022. 12. 8. 01:42
반복문을 제어하는 방법은 break와 continue를 사용하는 것이다. break를 사용해 반복문의 제어 흐름을 중단하고 루프를 빠져나오거나, continue를 사용해 반복문의 제어 흐름은 유지하되 코드 실행만 건너뛸 수 있다. # 1. break로 반복문 끝내기 1-1. while에서 break로 반복문 끝내기 i = 0 while True: # 무한 루프 생성 i += 2 if i == 8: # i가 8일 때 print(f"repeated {i // 2} times. escape the loop.") break # 반복문(무한 루프)을 끝냄 # 실행 결과 repeated 4 times. escape the loop. 1-2. for에서 break로 반복문 끝내기 for i in range(10): ..
-
10. if 조건문으로 특정 조건일 때 코드 실행하기Python/Grammar 2022. 12. 2. 10:32
# 1. if 조건문 사용하기 if 조건문은 의사코드(pseudo code)의 일종이다. 의사코드란 실제 프로그래밍 언어가 아닌 사람의 언어로 프로그래밍 언어를 표현한 것이다. 예를 들어 'x = 10'이라는 파이썬 코드를 '변수 x에 10 할당'과 같이 한글로 의사코드를 표현할 수 있다. 1-1. if 조건문의 기본 형태와 실행 흐름 : if 조건문은 if 조건식 다음줄에 들여쓰기 후 조건식이 만족할 때 실행할 코드를 넣는다. 조건식이 만족할 때 실행할 코드를 if 본문(if body)이라고 부른다. 1-2. if 조건문을 사용할 때 주의할 점 들여쓰기 : if 조건문 다음줄부터 형성되는 코드블럭(if body) 안에서는 같은 깊이로 들여쓰기를 해줘야 한다. IDLE 파이썬 셸에서는 자동 들여쓰기가 되..
-
9. 딕셔너리 만들기Python/Grammar 2022. 12. 2. 10:21
# 1. 딕셔너리 만들기 딕셔너리는 말 글대로 사전에서 단어를 찾듯이 키를 찾으면 값을 가져올 수 있다고 해서 딕셔너리라는 명칭이 붙었다. 딕셔너리를 만드는방법은 여러 가지가 있지만 가장 기본적인 방법으로 중괄호 안에 키: 값을 넣은 {키1: 값1, 키2: 값2, ...} 형태로 만든다. 각 키와 값은 콤마로 구분해주며, 키와 값은 1:1 대응되어 하나의 키에는 값을 하나만 지정할 수 있다. 따라서 키와 값을 "키-값 쌍(key-value pair)"이라고 부른다. 참고로 딕셔너리와 같은 키-값 쌍 형태의 자료형을 Hash, Hash Map, Hash Table 등으로 부르며 REDIS 저장기법 중 HSET의 H도 해시를 의미한다. 1-1. 빈 딕셔너리 만들기 : 빈 딕셔너리를 만들려면 중괄호 안에 아무..