[Python] 띄어쓰기 없이 입력되는 2차원 행렬을 2차원 배열로 입력 받는 방법 ☑️
·
Python
파이썬에서 string.split("") 호출 시ValueError: empty separator 오류 발생따라서 리스트로 변환 후 반복문으로 원소 하나씩 꺼내는 방법 사용 import sysn, m = map(int, sys.stdin.readline().split())# n은 행(row), m은 열(column)graph = []for i in range(n): a = list(sys.stdin.readline().rstrip()); b = [] for x in a: b.append(int(x)) graph.append(b) strip()양쪽(왼쪽 + 오른쪽) 공백 또는 지정한 문자를 제거 text = " Hello, Python! "result = text.strip..
[Python] 2차원 행렬을 90도 회전시키는 방법 ☑️
·
Python
n x n 의 2차원 행렬을 90도(시계방향) 회전시키는 방법 def rotate90(matrix): # 회전시키는 행렬은 nxn로 가정 n = len(matrix) newMatrix = [[0 for _ in range(n)] for _ in range(n)] for y in range(n): for x in range(n-1, -1, -1): newMatrix[y][n-1-x] = matrix[x][y] return newMatrix import sysn, m = map(int,sys.stdin.readline().split())print("[Original matrix]")matrix = [[row*m+col for col in range(m)] for row in range(n)]for ..
[Python] 배열을 선언하는 방법 ☑️
·
Python
* 연산자를 이용해 선언하는 방법1차원 배열을 선언할 때는 * 연산자를 이용하면 간단하게 선언할 수 있다.size = 10array = [0] * size 그러나, Python에서 * 연산자를 활용해 배열을 선언하는 경우 얕은 복사(shallow copy)를 활용하는 것이기 때문에 배열 내의 요소들이 같은 객체를 가리키게 된다. 그러므로 이러한 방식으로 2차원 배열을 선언하고 요소를 변경하게 되면 다른 요소들의 값도 같이 바뀌게 된다.cols = 5rows = 5array = [[0] * cols] * rows# [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]array[0][0] = 1# [[1,0,0,0,0],[1,0,0,0,0],[1,0,..
[Python] Collections 모듈 ☑️
·
Python
collections.Counter(리스트)리스트에서 요소들의 개수를 새고 {요소:개수} 형태의 딕셔너리로 값을 반환한다.collections.Counter() 함수로 반환된 딕셔너리 값끼리는 연산(+, -, &, |)이 가능하다.collections.Counter(리스트).most_common() 리스트 구성 요소들의 개수를 세고 최빈값 n을 반환한다 import collectionslist = [1,1,1,1,2,2,2,3,3,4,5]print(collections.Counter(list))# Counter({1: 4, 2: 3, 3: 2, 4: 1, 5: 1})print(collections.Counter(list).most_common())# [(1, 4), (2, 3), (3, 2), (4, 1..
[Python] 분수를 표현하는 방법 (Fraction) ☑️
·
Python
from fractions import Fraction 모듈을 import 해 와야 사용할 수 있다.from fractions import Fractionprint(Fraction(1,3) + Fraction(1,3))# 2/3 분수와 정수로 이루어진 수식의 결과는 분수로 나오지만, 소수가 포함된 수식은 결과가 소수로 나온다from fractions import Fractionprint(Fraction(1,4) + 1)# 5/4print(Fraction(1/4) + 1.25)# 1.5분자는 .numerator , 분모는 .denominator로 추출한다.from fractions import Fraction print(Fraction(1,3).numerator, Fraction(2,3).denomina..
[Python] int값을 각 자리수로 이루어진 list로 바꾸는 방법 ☑️
·
Python
def convert(n): origin = n values = [] while True: values.append(n%10) n = (n // 10) if n in range(10): values.append(n) break return valuestmp = bnums = [0,0,0]for i in range(3): num = tmp cnt = 0 while num//10 != 0: num = num//10 cnt = cnt+1 nums[cnt] = num tmp = tmp - pow(10,cnt)*num string과 list를 활용하는 방법 : i..
[Python] 문자열 관련 메서드 ☑️
·
Python
문자열.lower() : 문자열을 모두 소문자로 변환문자열.upper() : 문자열을 모두 대문자로 변환문자열.isupper() : 문자열이 모두 대문자인지 확인하여 True/False 반환len(문자열 or 리스트) : 문자열이나 리스트의 길이(요소 개수) 반환문자열.replace("Python","Java") : 문자열 내 "Python"을 "Java"로 모두 교체문자열.count(문자열) : 문자열 내 특정 문자열이 몇 번 나오는지 세기문자열.index() : 문자열에서 특정 문자의 첫 등장 위치(인덱스) 반환 # 문자열.find(문자열) : 없으면 -1을 반환# 문자열.index(문자열) : 없으면 오류 발생(프로그램 종료)
[Python] 문자열 자르기, 붙이기 ☑️
·
Python
1. 문자열을 잘라서 리스트로 만드는 방법 1) list() 함수를 이용list() 함수에 문자열을 넣으면 모든 문자(공백 포함)를 잘라서 리스트를 만들어준다.str = "I Love You"print(list(string))# ['I',' ','L','o','v','e',' ','Y','o','u'] 2) split() 함수를 이용문자열.split()을 사용하면 (구분자를 지정하지 않을 경우)공백을 기준으로 잘라서 리스트를 생성한다.split() 함수를 쓰면 문자열이 자동으로 리스트형으로 바뀌게 된다.string = "I Love You"print(string.split())# ['I','Love','You'] 2. 리스트를 합쳐서 문자열로 만드는 방법 1) join() 함수를 이용('구분자')..