스터디/알고리즘스터디-알까기🎯

[1]알고리즘 스터디 - 알까기 시작 _섹션2(1)

개발자 덕구🐾 2022. 2. 8. 22:24
728x90

타대학 사람들과 알고리즘 스터디를 시작하였다.

 

 

https://www.inflearn.com/course/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98-%EB%AC%B8%EC%A0%9C%ED%92%80%EC%9D%B4-%EC%BD%94%EB%94%A9%ED%85%8C%EC%8A%A4%ED%8A%B8/dashboard

 

파이썬 알고리즘 문제풀이 (코딩테스트 대비) - 인프런 | 강의

파이썬을 이용한 코딩테스트 문제풀이를 합니다., - 강의 소개 | 인프런...

www.inflearn.com

 

이 강의를 보고 공부하며
매주 수요일, 일요일 저녁 2시간마다 줌으로 모여, 복습 & 질의 응답을 가진다.
이를 기록하려고 한다.

 

 

 

한달동안 잘 마무리 할 수 있기를!!👏👏

 

 

 

by Annie SprattHire

 

 

 

섹션 2 - 코드 구현력 기르기

 

 

1번 문제 : k번째 약수

import sys
sys.stdin = open("input.txt", "rt") 
cnt = 0
n, k = map(int,input().split())
for i in range(1,n+1) :
    if n%i == 0 :
        cnt += 1
    if cnt == k :
        print(i)
        break
else : print(-1)

 

  • for else 구문 : for문이 break를 이용해 끝날 경우 else 문을 하지 않고 정상적으로 끝마칠 경우 else문을 실행한다.



2번 문제 : k번째 수

T = int(input())
for i in range(T) :
    n,s,e,k = map(int,input().split())
    nums = list(map(int,input().split()))
    ans = nums[s-1:e] 
    ans.sort()
    print("#%d %d" %(i+1,ans[k-1]))


- 특정 형태로 출력하는 구문 : #1 45 이런 형식으로 출력하려고 하는 경우 "#%d %d" 와 %(i+1, ans[k-1])를 print를 이용해 출력한다. 마치 c언어 같다.

 

 



3번 문제 : k번째 큰 수

import sys
from itertools import combinations
sys.stdin = open("input.txt", "rt") 
n,k = map(int,input().split())
nums = list(map(int,input().split()))
ans = set()

for num in combinations(nums,3) :
    ans.add(list(num)[0]+list(num)[1] + list(num)[2])
ans=list(ans)
ans.sort()
print(ans[-k])


- 중복 숫자일경우 무시하는 법 :

set이용 , set은 append가 아닌 add를 이용한다. set에는 sort기능이 없다.

 

 

4번 문제 : 대표값

import sys
sys.stdin = open("input.txt","r")
n = int(input())
numbers = list(map(int,input().split()))
avg = int((sum(numbers) / n ) + 0.5 ) # 평균을 구해 소수 첫째 자리에서 반올림 
similar = sys.maxsize # 가까운 정도 
for idx, x in enumerate(numbers) :
    tmp = abs(x-avg)
    if similar > tmp : 
        similar = tmp
        score = x
        index  = idx +1 # 해당 번호 저장 
    elif similar == tmp and score < x :
        score = x
        index  = idx +1 # 해당 번호 저장 

print(avg, index)


- 소수 첫째 자리에서 반올림 : 처음엔 round를 이용하였으나 이는 round_half_even이라서 반올림과 다름 0.5를 더한후 int를 이용해 소수점을 버리는 것이 반올림과 동일함

 

 

5번 문제 : 정다면체

import sys
from itertools import permutations
sys.stdin = open("input.txt","r")
n,m = map(int,input().split())
cnt = [0]*(n+m+1)

for i in range(1,n+1) : # 1부터 N까지 
    for j in range(1,m+1) : # 1부터 M까지 
        cnt[i+j] +=1
max_cnt = 0
for i in range(2, n+m+1) : # 가장 많은 빈도를 알아내기 
    if max_cnt < cnt[i] :
        max_cnt = cnt[i]
ans = []
for i in range(1, n+m+1) :  # 해당 빈도를 가진 값들 ans리스트에 넣기 
    if max_cnt == cnt[i] :
        ans.append(i)

ans.sort() # 정렬 후  
for a in ans:
    print(a,end = ' ')


- 내가 푼 코드 - sort할 필요 없이 어차피 정렬된 순서대로 돌아가므로 max_cnt = cnt[i]이면 여기서 바로 출력해도 맞음

 

 

 

6번 문제 : 자릿수의 합

import sys
from itertools import permutations
sys.stdin = open("input.txt","r")

N = int(input())
def digit_sum(x) :
    sum = 0
    for i in range(len(x)) :
        tmp = int(x[i])
        sum += tmp
    return sum


value = list(input().split())
max_value = 0
for i in value :
    tmp = digit_sum(i)
    if max_value < tmp :
        max_value = tmp 
        ans = i
print(ans)

 

이 코드는 수업의 코드와는 다르지만 정답코드다.

내가 생각해서 풀었다. 

이전보다 구현력이 오른것같아 기분이 좋다. 

 

 

 

 

 

 

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."

 

반응형