본문 바로가기

코딩테스트 with PYTHON

(31)
[python] 코딩테스트 대비 - 수열의 합 (경우의 수) 문제) 정답 코드) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import sys #sys.stdin = open("input.txt", 'r') n, m=map(int, input().split()) a=list(map(int, input().split())) lt=0#왼쪽 포인터 rt=1#오른쪽 포인터 tot=a[0]#합 cnt=0#카운트 while True: if tot
[python] 코딩테스트 대비 - 정렬된 리스트 합치기 문제) 답안코드) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 import sys #두리스트 더해서 sort() 하면 시간복잡도 nlog(n)-퀵소트 일경우 #정렬된 두 리스트 이기 때문에 앞에서 부터 하나씩 비교해 나가면 n번 반복으로 가능 #sys.stdin=open("input.txt", "r") n=int(input()) a=list(map(int, input().split())) m=int(input()) b=list(map(int, input().split())) p1=p2=0#리스트 인덱스 가르키는 포인터 역할 c=[]#결과 리스트 while p1
[python] 코딩테스트 대비 - 카드 역배치(리스트 뒤집기) 문제) 답안 코드) 1 2 3 4 5 6 7 8 9 10 11 12 13 import sys #sys.stdin=open("input.txt", "r") a=list(range(21))#리스트 생성 for _ in range(10): s, e=map(int, input().split())#구간 입력 for i in range((e-s+1)//2):#앞에서부터, 뒤에서 부터 접근하며, 뒤집기 a[s+i], a[e-i]=a[e-i], a[s+i] a.pop(0) for x in a: print(x, end=' ') Colored by Color Scripter cs
[python] 코딩테스트 대비 - 문자열에서 숫자만 추출 문제) 답안코드) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import sys #sys.stdin=open("input.txt", "r") s=input() res=0#숫자만 추출된 결과 for x in s: if x.isdecimal():#x가 0~9숫자인지 판별해주는 함수. res=res*10+int(x)#숫자화 print(res) cnt=0 for i in range(1, res+1):#약수 갯수 계산 if res%i==0: cnt+=1 print(cnt) Colored by Color Scripter cs
[python] 코딩테스트 대비 - 회문 문자열 문제) 답안 코드) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 import sys #sys.stdin=open("input.txt","rt") #방법1 def check(string): string=str.upper(string)#대문자화 if string==string[::-1]:#뒤집은것과 비교 return "YES" else: return "NO" N=int(input()) for i in range(N): print("#"+str(i+1)+" "+check(input())) #방법2 n=int(input()) for i in range(1, n+1): str=input() str=str.upper()#대문자화 for ..
[python] 코딩테스트 대비 - 점수계산 문제) 답안 코드) 1 2 3 4 5 6 7 8 9 10 11 12 13 import sys #sys.stdin=open("input.txt","rt") N=int(input()) box=list(map(int,input().split())) weight=1 score=0 for i in box: if i==1:#맞췄을때 score+=weight*i weight+=1 else:#맞추지 못했을때 weight=1 print(score) cs
[python] 코딩테스트 대비 - 규칙구현 문제) 정답 코드) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import sys #sys.stdin=open("input.txt", "r") res=0#정답 n=int(input()) for i in range(n): tmp=input().split() #문자열 리스트로 저장 tmp.sort() #오름차순 정렬 a, b, c=map(int, tmp) if a==b and b==c:#3개 모두 같은 경우 money=10000+(a*1000) elif a==b or a==c:#2개만 같은경우 money=1000+(a*100) elif b==c:#2개만같은경우 money=1000+(b*100) else:#모두 다른경우 money=c*100#sort했기 때..
[python] 코딩테스트 대비 - 소수뒤집기 문제) 답안코드) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 import sys #sys.stdin=open("input.txt", "r") def reverse(x):#뒤집은 숫자 리턴 res=0 while x>0: #ex) 120 ㅡ> # 1단계:(t=0 res=0*10+0=0 x=12) # 2단계:(t=2 res=0*10+2=2 x=1) # 3단계:(t=1 res=2*10+1=21 x=0) t=x%10#첫번째 자리수 res=res*10+t#뒤집은 결과 x=x//10#다음 자리 접근 return res def isPrime(x):#소수인지 확인 if x==1:#1은 소수가 아님 return False fo..