목록전체 글 (317)
지나가던 개발자

def is_palindrome(a): return a == a[::-1] def jinsu(n, m): hihi = [] while True: if n // m == 0: hihi.append(n) break hihi.append(n%m) n = n // m hihi.reverse() return "".join(map(str,hihi)) n = int(input()) printed = False for i in range(2, 11): if is_palindrome(jinsu(n,i)): printed = True print(i, jinsu(n, i)) if not printed: print("NIE")

def binary_search(nums, target): left, right = 0, len(nums)-1 while left target: right = mid - 1 else: return 1 return 0 input() have = sorted(list(map(int, input().split(" ")))) input() cards = list(map(int, input().split(" "))) for i in cards: print(binary_search(have, i), end=" ") 이분 탐색 알고리즘을 사용했다.

for i in range(int(input())): print(sorted(list(map(int, input().split(" "))), reverse=True)[2])

input() s = input() hidden_numbers = [] is_number = False num = "" for i in s: if i not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: if len(num) < 7 and len(num) != 0: hidden_numbers.append(int(num)) num = "" continue num += i if len(num) < 7 and len(num) != 0: hidden_numbers.append(int(num)) print(sum(hidden_numbers)) 13번 줄의 조건문을 안 썼다가 틀렸습니다가 떴다. 단어가 숫자로 끝난 경우에도 히든 넘버에 포함되기에 13번 14번 줄..

C의 for문은 다음과 같은 형식으로 구성된다. for (초기식; 조건식; 증감식) { 실행문; } 초기식은 for문의 loop에 사용될 변수의 초기값을 지정하는 것이고, 조건식은 조건식이 true일 때에만 실행하라는 것이고, 증감식은 초기값을 지정한 변수의 값을 증가 혹은 감소시키는 것이다. 이렇게 말이다. #include int main() { for (int i=1; i

#include int main() { int time = 0; for (int i=0; i

def hab(n): return str(sum(list(map(int, list(n))))) while True: n = input() if n == "0": break while True: if len(n) == 1: print(n) break n = hab(n)

for i in range(int(input())): ox = input() continuity = 1 grade = 0 for j in range(len(ox)): if ox[j] == "O": grade += continuity continuity += 1 else: continuity = 1 print(grade) 맨날 글 쓰기 귀찮아서 임시저장 해두는데 임시저장 글이 90일까지밖에 저장이 안 된다는 사실을 깨닫고 부랴부랴 글 쓴다..

from itertools import combinations while True: s = input().split(" ")[1:] if s == []: break for i in combinations(s, 6): print(" ".join(i)) print("") itertools 진짜 너무 편한 것 같다.. PS할때 모듈 쓰면 안되는게 스탠다드긴 한데, 나는 이미 잘 만들어진 기본 모듈 놓고 왜 직접 이걸 구현하는지 모르겠다. 특히 파이썬에서는. 나도 C할때는 알고리즘 가지고 다 한다! 이 글을 쓰는 데 도움이 되었던 자료: https://juhee-maeng.tistory.com/91 (Python) 순열, 조합, 중복순열, 중복조합 쉽게 구현하기 (Python) 순열, 조합, 중복순열, 중복조합..

def jinsu(n, m): s = 0 while True: if n // m == 0: s += n break s += n%m n = n // m return s for i in [2992, 2993, 2994, 2995, 2996, 2997, 2998, 2999]: print(i) for i in range(3000, 10000): if sum(list(map(int, list(str(i))))) == jinsu(i, 12) == jinsu(i, 16): print(i) 시간초과가 뜨지 않을까? 생각했지만 괜한 걱정이었다. 잘 된다. jinsu 함수는 저번에 만든 진수 변환기 코드를 조금 응용해서배껴서 만들었다. https://developer-next-to-you.tistory.com/11?cat..

s = input() angle_bracket = False to_print = "" for i in s: if i == "": angle_bracket = False print(i, end='') continue if angle_bracket: print(i, end='') continue if i == " ": print("".join(list(reversed(to_print))), end=' ') to_print = "" continue to_print += i print("".join(list(reversed(to_print)))) 꺽쇠의 안쪽인지 아닌지를 True or False 형태로 판별한 뒤, 뒤집은 문자열 혹은 뒤집지 않은 문자열을 출력한다. 16번라인~19번라인... [틀렸습니다]가 떠..

s1 = input() s2 = input() lcs = [[0 for col in range(len(s1)+1)] for row in range(len(s2)+1)] for i in range(1, len(s2)+1): for j in range(1, len(s1)+1): if s1[j-1] == s2[i-1]: lcs[i][j] = lcs[i-1][j-1]+1 continue lcs[i][j] = max(lcs[i-1][j], lcs[i][j-1]) print(max(sum(lcs, []))) 이 문제를 풀고 솔브닥 골드가 되었다...! LCS를 구하는 알고리즘을 설명한 글은 밑에다가 첨부해 놓겠다. 내가 글을 하나 쓸까 하는 생각도 했지만 밑의 블로그가 너무 잘 써서 그걸 보는 편이 나을 듯 하다...

while True: try: print(input()) except: break 11718번 문제와 정답 코드가 정확히 일치한다. 11718번은 브론즈V였는데 이건 왜 브론즈II인지 알 수가 없다.

group_word = 0 for i in range(int(input())): is_group_word = True word = input() wordAlphabet = [] for j in word: if j not in wordAlphabet: wordAlphabet.append(j) if len(wordAlphabet) == len(word) or len(wordAlphabet) == 1: group_word += 1 continue for j in range(len(wordAlphabet)): if j == 0 or j == len(wordAlphabet)-1: if len([x for x in word.split(wordAlphabet[j]) if x != '']) == 1: continue ..

from itertools import combinations from string import ascii_lowercase l, c = map(int, input().split(" ")) alphabets = sorted(input().split(" ")) vowels = ["a", "i", "u", "e", "o"] consonents = list(set(ascii_lowercase)-set(vowels)) for i in list(combinations(alphabets, l)): if len([x for x in i if x in vowels]) >= 1 and len([x for x in i if x in consonents]) >= 2: print("".join(i)) 파이썬은 사실상의 PS ..

print(str(bin(int(input())+1)[3:]).replace("0", "4").replace("1", "7")) 골드V문제를 한줄코딩하다니... 라기보단 내가 푼 것이 아니다. 나는 구현만 했고, 푼 건 다른 사람이다. 문제를 보고 뭔말인지 모르겠어서 블로그를 찾아봤는데, 이런 글이 눈에 띄었다. 분명 패턴이 있는데 이 패턴을 어떻게 정리하고 구현할지 고민하다가 K+1의 이진수에서 가장 큰 자리수를 없애면 매칭이 된다는 것을 알게 되었다. 즉, K가 5일때 4와 7로 만들 수 있는 5번째 작은 수는 74인데 위의 그림에서 74를 7을 1로 표현하고 4를 0으로 표현한 이진수로 보았을 때 10으로 되어있다. 이때 5+1(=6)의 이진수는 110이고 여기서 가장 큰 자리수인 1을 없애면 10..

while True: try: print(input()) except: break n개의 줄에 입력되는데, 이 n을 알려주지 않아 상당히 곤란했던 문제이다. 여기서 try-except문을 쓴 이유는 만약 줄이 끝나면 EOFError가 뜰 것이기 때문이다. EOFError는 End-Of-File의 약자로, 입력이 끝나 데이터가 없을 때 나는 에러이다. 이 글을 쓰는 데 도움이 되었던 자료: https://heewon9809.tistory.com/65 [백준 파이썬] #11718: 그대로 출력하기 https://www.acmicpc.net/problem/11718 11718번: 그대로 출력하기 입력이 주어진다. 입력은 최대 100줄로 이루어져 있고, 알파벳 소문자, 대문자, 공백, 숫자로만 이루어져 있다. ..

grade = [int(input()), int(input()), int(input()), int(input()), int(input()), int(input()), int(input()), int(input())] print(sum(sorted(grade)[3:])) toPrint = [] for i in sorted(grade)[3:]: toPrint.append(grade.index(i)) for i in sorted(toPrint): print(i+1, end=' ') 이게 왜 실버V? 아무리 높게 잡아도 브론즈2 정도인 것 같은데... 어쩌면 파이썬으로 풀어서 그럴지도 모른다. 갓-파이썬

코딩을 할 때에, 정수 리스트의 전체의 합을 구해야 하는 일이 생긴다. 안 생겼다면 유감이지만 그건 코딩을 많이 안 해본 거다.. 간단한 알고리즘으로는 다음과 같은 코드를 생각할 수 있다. l = [1, 2, 3, 4, 5] s = 0 for i in l: s += i print(s) 이렇게 구할 수 있다. 그런데 이 방법은 너무 길다. 긴 코드를 써야 한다. Pythonic한 방법이라고 보기 힘들다. 파이썬에서는 이렇게 코드를 짤 수 있다. sum(리스트)

n, m = map(int, input().split(" ")) if len(str(n))*n

A = [False, False] + [True] * 4000000 for i in range(2, 4000000): if A[i]: for j in range(i+i, 4000000, i): A[j] = False a, b, d = map(int, input().split(" ")) sossu = 0 for i in range(a, b+1): if A[i]: if str(d) in str(i): sossu += 1 print(sossu) 에라토스테네스의 체 알고리즘을 사용했다. 예전에 풀었던 9842번 문제가 떠오르는 코드다. https://developer-next-to-you.tistory.com/205 [Python] 백준 9842번(Prime) 문제 풀이 def nthPrime(n): a = [..

n = int(input()) if n [ BOJ / Python ] 2226번 이진수 이번 문제는 DP를 통해 해결하였다. 수열은 1 -> 01 -> 1001 -> 01101001 -> 1001011001101001 -> ... 으로 구성된다. 이때 만들어진 문자열들을 반으로 잘라 보면 다음과 같은 규칙을 찾을 수 있다.앞쪽과 뒷쪽 velog.io

for i in range(int(input())): n, m = map(int, input().split(" ")) zeros = 0 for i in range(n, m+1): zeros += str(i).count("0") print(zeros) 이게 왜 맞았는지 의문이 든다.. 진짜 모르겠다.. 나는 당연히 시간 초과가 날 줄 알았는데.. T는 20까지, M은 1,000,000까지 입력될 수 있으니 반복문이 최대 20,000,000번 돌아갈 수 있는 코드인데 말이다. 이게 왜 맞았지? 맞.왜.틀?을 넘은 틀.왜.맞?의 등장...

if int(input()) in [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824]: print(1) else: print(0) 이게 맞나... https://developer-next-to-you.tistory.com/121 [Python] 백준 10870번(피보나치 수 5) 문제 풀이 print([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ..

from collections import Counter import sys def modefinder(numbers): c = Counter(numbers) order = c.most_common() maximum = order[0][1] modes = [] for num in order: if num[1] == maximum: modes.append(num[0]) return modes nums = [] for i in range(int(sys.stdin.readline())): nums.append(int(sys.stdin.readline())) print(round(sum(nums)/len(nums))) print(sorted(nums)[len(nums)//2]) m = modefinder(num..

import sys nums = [] for i in range(int(sys.stdin.readline())): nums.append(int(sys.stdin.readline())) for i in sorted(nums): sys.stdout.write(str(i)) sys.stdout.write("\n") 비내림차순이라고 어렵게 말을 해놨지만, 사실 오름차순과 같은 의미이다(非내림차순인가)... 2751번과 코드가 완전히 똑같다. https://developer-next-to-you.tistory.com/206 [Python] 백준 2751번(수 정렬하기 2) 문제 풀이 import sys nums = [] for i in range(int(sys.stdin.readline())): nums.appe..

import sys nums = [] for i in range(int(sys.stdin.readline())): nums.append(int(sys.stdin.readline())) for i in sorted(nums, reverse=True): sys.stdout.write(str(i)) sys.stdout.write("\n") 저번에 푼 2751번(수 정렬하기 2) 문제와 거의 유사하다. 그냥 5번 줄에서 reverse=True를 추가해서 내림차순으로 정렬되게 하였다.

import sys nums = [] for i in range(int(sys.stdin.readline())): nums.append(int(sys.stdin.readline())) for i in sorted(nums): sys.stdout.write(str(i)) sys.stdout.write("\n") 이 문제를 무려 6개월동안이나(!) 못 풀었다. 이렇게 쉬운 문제를.. 파이썬의 기본적인 sort 알고리즘은 Tim Sort 알고리즘이다. Tim Sort는 O(nlogn)의 시간 복잡도를 가진다. 이는 퀵 소트와도 같은 시간 복잡도로, 왠만한 문제는 다 풀린다고 보면 된다. 그런데 이렇게 떴다!! 시간 초과! 그래서 뭐가 문제지 하고 안 풀고 있다가 오늘 문득 sys가 기억이 나서.. 빠른 입력을..

def nthPrime(n): a = [False, False] + [True] * 999998 Primes = [] for i in range(2, 999998): if a[i]: Primes.append(i) for j in range(i+i, 999998, i): a[j] = False return Primes[n-1] print(nthPrime(int(input()))) https://wlghsp.tistory.com/17 [Python] n번째 소수 찾기 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 def nthPrime(n): # To-do # 충분히 큰 크기(1000000 정도)를 가진 리스트를 생성하고 # 에라토스테네스의 체를 사용해 n번.. wlghsp..