AttackOnNunu

Once more into the fray


  • 홈

  • About

  • 태그

  • 카테고리

  • 아카이브

  • 검색

(파이썬 S/W 문제해결 기본) List1 - 4828번 4831번 4834번 4835번

작성일 2019-08-06 In ALGORITHM 🎯 , SW 아카데미 댓글:

4828번 - min max

  • 시간 : 10개 테스트케이스를 합쳐서 Python의 경우 2초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내

한 줄을 한번에 입력 받는 input() 말고 띄어쓰기 마다 입력받는 방법이 없을까?
sys.stdin.readline() 을 사용하면 시간 단축은 많이 된다는 것 같다

import sys

T = int(input()) # 1 <= T <= 50

for test_case in range(1, T+1):
N = int(input()) # 5 <= N <= 1000
max = 1; min = 1000000 # 1<= a <= 1000000
a = [int(num) for num in sys.stdin.readline().split()] # = [int(num) for num in input().split()] # = list(map(int, input().split()))

for num in a:
if num>max:
max = num
if num<min:
min = num

print("#{} {}".format(test_case, max-min))


4831번 - 전기버스

  • 시간 : 10개 테스트케이스를 합쳐서 Python의 경우 2초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내

자동차경주대회 문제랑 비슷

T = int(input()) # 1 <= T <= 50

for test_case in range(1, T+1):
K, N, M = map(int, input().split()) # k:최대 이동 거리, n:총 정거장 수 , m:충전기 정류장 수
bus_stop = [int(stop) for stop in input().split()]
charge_stop = [0]\*(N+1)
for i in range(M):
charge_stop[bus_stop[i]] = 1

bus_position = 0
max_stop = K
cnt=0

while True:
check = 0
for i in range(bus_position+1, max_stop+1):
if charge_stop[i] == 1:
bus_position = i
else:
check += 1

if check == K:
cnt = 0
break

cnt += 1
max_stop = bus_position + K

if max_stop >= N:
break

print('#%s %d'%(test_case, cnt))


4834번 - 숫자 카드

  • 시간 : 10개 테스트케이스를 합쳐서 Python의 경우 2초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내

카드 장수가 같을 때 큰 숫자를 선택해야하는 조건을 주의

T = int(input()) # 1 <= T <= 50

for test_case in range(1, T+1):
N = int(input()) # 5 <= N <= 100
a = [int(num) for num in input()] # 0 <= a <= 9

cards = [0] * 10
max_cnt = 0
max_idx = 0

for i in range(N):
cards[a[i]] += 1

if cards[a[i]] > max_cnt:
max_cnt = cards[a[i]]
max_idx = a[i]
elif cards[a[i]] == max_cnt:
if a[i] > max_idx:
max_idx = a[i]

print("#{} {} {}".format(test_case, max_idx, max_cnt))


4835번 - 구간 합

  • 시간 : 10개 테스트케이스를 합쳐서 Python의 경우 2초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내
시간복잡도 : 정렬 sort() - O(nlogn)
최대,최소 max(),min() - O(n)
T = int(input()) # 1 <= T <= 50

for test_case in range(1, T+1):
N, M = map(int, input().split()) # 10 <= N <= 100 , 2 <= M <= N
a = [int(num) for num in input().split()] # 1 <= a <= 10000

sum_list = []
for i in range(N - M + 1):
sum_list.append(sum(a[i:i + M]))

print("#{} {}".format(test_case, max(sum_list) - min(sum_list)))


(SW Expert Academy) 객체지향 - 6203번 6208번 6217번 6223번

작성일 2019-08-05 In ALGORITHM 🎯 , SW 아카데미 댓글:

1번 - 6203번

  • 시간 : 1개 테스트케이스를 합쳐서 Python의 경우 1초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내

성적 총합 출력

class subject:
def **init**(self, kor, eng, math):
self.**kor = kor
self.**eng = eng
self.\_\_math = math

def total(self):
return self.__kor+self.__eng+self.__math

score = input().split(', ')

stduent = subject(int(score[0]),int(score[1]),int(score[2]))
print("국어, 영어, 수학의 총점: {}".format(stduent.total()))

2번 - 6208번

  • 시간 : 1개 테스트케이스를 합쳐서 Python의 경우 1초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내

국적 두 번 출력

class Korean:
def printNationality(self):
print("대한민국")

korean = Korean()
korean.printNationality()
korean.printNationality()

3번 - 6217번

  • 시간 : 1개 테스트케이스를 합쳐서 Python의 경우 1초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내

이렇게 하는게 맞는건지 잘 모르겠다…

class Student:
"""Parnet/Super class"""
\_name1 = "홍길동"
\_name2 = "이순신"

@property
def name(self):
return self._name

@name.setter
def name(self, name):
self._name = name

def show(self):
print("이름: "+self._name1)

class GraduateStudent(Student):
"""Child/Sub class"""
\_\_major = "컴퓨터"

def __init__(self):
self.__name = super()._name2

def show(self):
print("이름: {}, 전공: {}".format(self.__name, self.__major))

Student().show()
GraduateStudent().show()

4번 - 6223번

  • 시간 : 1개 테스트케이스를 합쳐서 Python의 경우 1초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내

원의 면적을 구할 때, 파이(pi)를 파이썬의 math를 사용하여 계산하려 했지만 출력 결과는 소수점 둘째 자리까지인데 버림이 되어있다.
round() 를 사용하여 반올림하면 결과값이 다르게 나와서 파이를 3.14로 계산 하였다.
round() 함수에서 반올림은 사사오입 원칙을 따른다는 것을 기억!!

import math

class Circle:
\_\_radius = 2

def area(self):
return 3.14*(self.__radius**2)

print("원의 면적: {}".format(Circle().area()))

(SW Expert Academy) 문자열 - 6232번 6239번 6241번 6678번 6243번 6248번

작성일 2019-08-05 In ALGORITHM 🎯 , SW 아카데미 댓글:

1번 - 6232번

  • 시간 : 1개 테스트케이스를 합쳐서 Python의 경우 1초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내

나눗셈 몫으로 정수를 원하면 ‘//‘ 사용!

def is_palindrome(word):
word_list = list(word)
length = len(word)
for i in range(0,length//2):
if word_list[i] != word_list[length-1-i]:
return False
return True

word = input()
print(word)
if(is_palindrome(word)):
print("입력하신 단어는 회문(Palindrome)입니다.")
else:
print("입력하신 단어는 회문(Palindrome)이 아닙니다.")

2번 - 6239번

  • 시간 : 1개 테스트케이스를 합쳐서 Python의 경우 1초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내

단어 역순 출력

print(' '.join(input().split(' ')[::-1]))

3번 - 6241번

  • 시간 : 1개 테스트케이스를 합쳐서 Python의 경우 1초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내
URL = 'http://www.example.com/test?p=1&q=2'
protocol = URL[:URL.find('://')]
host = URL[URL.find('://')+3:URL.rfind('/')]
others = URL[URL.rfind('/')+1:]

print("protocol: {}\nhost: {}\nothers: {}".format(protocol,host,others))

4번 - 6678번

  • 시간 : 1개 테스트케이스를 합쳐서 Python의 경우 1초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내

아래와 같은 방법으로 제출하면 메모리 에러가 뜬다. 즉, 아무 입력 없이 엔터를 눌러도 종료되지 않고 계속 돌아간다는거 같은데
다른 IDE를 사용하여 프로그램을 돌려보면 정상적으로 작동된다

while True:
words = input()
if words=='':
break
print(">> {}".format(words.upper()))

5번 - 6243번

  • 시간 : 1개 테스트케이스를 합쳐서 Python의 경우 1초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내

.split(‘ ‘)으로 공백 구분, set() 으로 중복값 없애고 sorted()로 순서를 정렬

print(','.join(sorted(list(set(input().split(' '))))))

7번 - 6248번

  • 시간 : 1개 테스트케이스를 합쳐서 Python의 경우 1초
  • 메모리 : 힙, 정적 메모리 합쳐서 256MB 이내, 스택 메모리 1MB 이내
raw_str = list(input())
for i in range(0, len(raw_str), 2):
print(''.join(raw_str[i]), end='')
1…192021…33
NUNU

NUNU

개인적으로 공부하면서 정리한 내용들을 블로그에 남기고 있습니다.
99 포스트
18 카테고리
53 태그
RSS
Creative Commons
© 2021 NUNU
Powered by Hexo v3.9.0
|
Theme – NexT.Mist v7.2.0