본문 바로가기

Pythonic16

[파이썬을 파이썬답게] 파일 입출력 간단하게 하기 EOF (end of file) 을 체크할 필요가 없고 close할 필요도 없다. 이미 사용하고 있긴 하지만 다시 체크 2021. 3. 8.
[파이썬을 파이썬답게] 가장 큰 수, inf 설정하기 max_value = float('inf') min_values = float('-inf') 파이토치 save criterion 설정할때 9999999, -99999 대신에 쓰면 될듯 2021. 3. 8.
[파이썬을 파이썬답게] class의 자동 string casting class Coord(object): def __init__(self, x, y): self.x, self.y = x, y point = Coord(1, 2) print( '({}, {})'.format(point.x, point.y) ) # 또는 def print_coord(coord): print( '({}, {})'.format(coord.x, coord.y) ) print_coord(point) Using __str__ 메서드 class Coord(object): def __init__ (self, x, y): self.x, self.y = x, y def __str__ (self): return '({}, {})'.format(self.x, self.y) point = Coord(1, 2) 2021. 3. 8.
[파이썬을 파이썬답게] binary-search (bisect) 2021. 3. 8.
[파이썬을 파이썬답게] flag Or for-else for-else 문 import math numbers = [5,1,2,3,1] multiplied = 1 for number in numbers: multiplied *= number print(math.sqrt(multiplied), int(math.sqrt(multiplied))) if math.sqrt(multiplied) == int(math.sqrt(multiplied)): print('found') break else: print('not found') 일반 flag 변수 사용문 import math numbers = [5,1,2,3,1] multiplied = 1 flag = True for number in numbers: multiplied *= number if math.sqrt(mu.. 2021. 3. 8.
[파이썬을 파이썬답게] 가장 많이 등장하는 알파벳 찾기 my dirty code with for x 2 from collections import Counter my_str = input().strip() c = Counter(my_str).most_common() max_num = 0 for k, v in c: if v > max_num: max_num = v res = "" for k, v in c: if v == max_num: res+=k print("".join(sorted(res))) import collections my_list = [1, 2, 3, 4, 5, 6, 7, 8, 7, 9, 1, 2, 3, 3, 5, 2, 6, 8, 9, 0, 1, 1, 4, 7, 0] answer = collections.Counter(my_list) print(.. 2021. 3. 8.
[파이썬을 파이썬답게] 순열과 조합 from itertools import permutations def solution(mylist): return list(permutations(sorted(mylist))) def permute(arr): result = [arr[:]] c = [0] * len(arr) i = 0 while i < len(arr): if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] result.append(arr[:]) c[i] += 1 i = 0 else: c[i] = 0 i += 1 return result from itertools import permutations pool .. 2021. 3. 8.
[파이썬을 파이썬답게] 2d 리스트를 1d 리스트로 만들기 from itertools import chain def solution(mylist): return list(chain(*mylist)) 2021. 3. 8.
[파이썬을 파이썬답게] 곱집합 구하기 - itertools.product itertools.product for 문 사용하지 않고 product 구하기 import itertools iterable1 = 'AB' iterable2 = 'xy' iterable3 = '12' print(list(itertools.product(iterable1, iterable2, iterable3))) # output # [('A', 'x', '1'), ('A', 'x', '2'), ('A', 'y', '1'), ('A', 'y', '2'), ('B', 'x', '1'), ('B', 'x', '2'), ('B', 'y', '1'), ('B', 'y', '2')] 리스트로 해줘야 함 2021. 3. 8.