본문 바로가기

IT To do and To was

22년 11월 19일_python3 예외처리, list slice 객체 클래스 및 기초 개념 뇌새김, 오픽 예상문제 정리

728x90
반응형

토요일[나는 평일 또한 주말이다]

 

1. python 강의

2. 기존에 이해하지 못했던 join 2개 문제 이해하기 (https://velog.io/@sheltonwon/SQL%EC%97%B0%EC%8A%B5-%EA%B7%B8%EB%A3%B9%EB%B3%84-%EC%A1%B0%EA%B1%B4%EC%97%90-%EB%A7%9E%EB%8A%94-%EC%8B%9D%EB%8B%B9-%EB%AA%A9%EB%A1%9D-%EC%B6%9C%EB%A0%A5%ED%95%98%EA%B8%B0)

3. opic 

4. 이것이

 

1>

--예외처리

text = '100%'
try :
    number = int(text)
except ValueError:
    print('{}는 숫자가 아니네요'.format(text))
def self_pop_print(list, index):
    try :
        print(list.pop(index))
    except IndexError:
        print('{} index의 값을 가져올 수 없습니다.'.format(index))
        
self_pop_print([1,2,3],5)

except 뒤에 아무이름도 적지 않으면 무슨 에러가 나도 except문이 실행됨

 

에러의 오류 메시지를 print하고자 할 때는

try :
    list = []
    print(list[0])
    
    text = 'abc'
    number = int(text)
    
except Exception as ex:
    print('에러가 발생하였습니다. 이유는:',ex)
def rsp(main, yours) :
    allowed = ['가위', '바위', '보']
    if main not in allowed:
        raise ValueError
    if yours not in allowed:
        raise ValueError
        
a, b = input().split()
try  :
    rsp(a,b)
except ValueError:
    print('잘못된 값을 넣은 거 같습니다.')

임의로 예외처리 발생 시키기

class_st = {'1반' : [124,26,178,189,199],'2반':[167,189,178,193,111]}

try :
    for class_s, student in class_st.items():
        for student in student:
            if student > 190 :
                print('{}에 {}인 친구가 있습니다'.format(class_s, student))
                raise StopIteration
except :
    print("---종료---")

bool(0) = False

그 외는 True

 

bool([]) = False

리스트에 값이 채워져 있으면 True

n = input()

try :
    if bool(n) :
        print(n+"으로 닉네임을 생성하였습니다.")
    else : 
        raise StopIteration
except :
    print("문자 및 숫자를 입력해주세요")

input()에서 값이 들어오지 않을 경우 boolean으로 들어오는 것을 이해하여

n = input() or "문자 및 숫자를 입력해주세요"
print(n)

이렇게 간단하게 코드를 만들 수 있음

 

갖고있는 list에 값을 알고 있으며 그에 해당하는 index값을 알고싶을 경우

 

list명.index(값) //인덱스 수

 

list 값 넣기

list명.append(숫자) //append is only one argument

list명.extend([숫자, 숫자]) // not only one argument

list명.insert(인덱스명, 숫자) // 해당 인덱스에 해당 숫자를 insert 함 (+index명을 -1로하면 마지막에 추가됨

 

정렬

list명.sort()

list명.reverse()

 

list와 문자열

문자열을 받은 후 해당 변수[인덱스값]을 기입할 경우 해당 index의 문자가 나온다.

활용 예시 )

n = "hellllo"
try :

    for i in range(len(n)):

        if n[i-1] == n[i]:
            print("*", end='')
        else: 
            print(n[i], end ='')
except :
        print(n[i], end='')

문자열을 리스트로 바꿔서 저장할 수 있음

n = "hellllo"

print(n.index("l")) #2 

n_list = list(n)

print(n_list) #['h', 'e', 'l', 'l', 'l', 'l', 'o']

for i in n :
    print(i)

배열을 이어붙이고 싶을 때는 

"이어붙일 때 문구".join(배열이름)

 

list slice

list = [1,3,4,5,2]

list[1:4] # 3,4,5
list[1:] # 3,4,5,2

list slice step

list[첫번째index: 마지막index:증감]

list slice 값 변경

list = list(range(10)) # [0,1,2,3,4,5,6,7,8,9]

del list[1:2]

print(list)  # [0,2,3,4,5,6,7,8,9]

list[4:5] = [11]

print(list) # [0,2,3,4,11,6,7,8,9]

list[2:7] = [9]

print(list) # [0,2,9,8,9]

 

type 쉽게 아는 법

 

ininstance(변수명, 판별하려는type) # True : 맞음 / false : 틀림

 

class와 메소드 생성

class hi():
    '''자기소개'''

person1 = hi()

person1.name = "박하률"

def introduce(person):
    print("안녕하세요 제 이름은 {} 입니다.".format(person.name))
    
introduce(person1)

hi.introduce = introduce

person1.introduce()

print(type(person1))

 

class > instanse

 

모델링

예시 )

class Human():
    '''인간'''
    
def create_human(name, weight):
    person = Human()
    person.name = name
    person.weight = weight
    
    return person
    
Human.create_human = create_human

person =Human.create_human("하률",59)

def eat(person):
    person.weight += 3
    print("{}은 {}kg이 되었습니다.냠냠".format(person.name, person.weight))

def run(person):
    person.weight -= 1
    print("{}은 {}kg이 되었습니다.헥헥".format(person.name, person.weight))
    
Human.eat = eat
Human.run = run

person.eat()
person.eat()
person.run()

2>

(SELECT MEMBER_ID FROM REST_REVIEW
                       GROUP BY MEMBER_ID
                        ORDER BY COUNT(MEMBER_ID) DESC
                        LIMIT 1)

URL에 있는 코드를 이해하려 했지만 내가 이전에 했던 거에 비해 복잡해서 다시 기존에 했던 코드로 review했다.

보니까 내가 기재한 URL에서는 RANK함수를 사용했는데 해당 기능은 기준에 따라 등수를 매기는 함수이다.

쓰이는 문법은 아래와 같다.

SELECT 컬럼명1, 컬럼명2, RANK() OVER (ORDER BY 컬럼명 [DESC/ASC]) 새 컬럼명

활용하면 좋긴 할듯

 

3>

OPIC 꿀팁

선택 시 

혼자사는 것으로 선택

취미는 영화,

운동은 조깅, 걷기, 요가, 안함

 

예상출제문제

1. Introduce myself
2. The story of the current house
3. Changes made to the house recently
4. Comparison of the suitable house and current house
5. What to wear for yoga
6. After experiencing yoga for the first time,
7. Persistent experience in memory during yoga sessions
8. (돌발문제) Technology/device that people in Korea use the most
9. Previous and Current Technology/Device Reports and Changes
10. Technical/device-related problems and experiences resolved.
11. (Role play) Ask your friend to go camping with 3-4 questions over the phone
12. A situation where you can't go camping because of the weather. Explain to a friend and give 2-3 alternatives
13. The experience of canceling a trip or appointment due to weather, etc.
14. (돌발문제) Activities performed by Korean citizens to maintain health
15. How people in Korea maintained their health in the past and how they maintain their health today

 

4>

숫자카드게임

게임 설명 )

N * M 의 카드 더미가 무작위로 input되는데

해당 행 중 하나의 카드를 뽑는데, 해당 행 중 가장 작은 숫자를 뽑아야한다. 그래서 행중 가장 큰수가 있는 것을 선택 해야한다.

 

--input

N M

M개의 카드 더미

N개의 행

예시 )

3 3

1 3 6

4 4 2 

2 4 2

 

답안

n, m = map(int, input().split())

result = 0

for i in range(n):
	data = list(map(int, input().split())
    min_value = min(data) #현재 행 중 가장 작은 수 
    result = max(result, min_value) # 가장 작은수 중 가장 큰 수를 찾음
    
 print(result)

 

내 답안

n, m = map(int, input().split())

result = 0


for i in range(n): # 열만큼 input 받기
    a = list(map(int, input().split())) # 행 뽑기
    a.sort()
    if result < a[0] :
        result = a[0]
        
print(result)

더 직관적이지 않은가..?!

min과 max함수를 잘 활용하면 답안처럼 떠올릴 수도 있을 거같다..

 

 

 

내일 쪽지문제

해비 유저가 소유한 장소 시험 보자 백엔드 상반기 문제였다! 오호라..ㅎㅎㅎ

// yesterday wished to today list.

. 병원 전화하기_월요일에 하길

. 도서관에서 딴짓하지 않기_조금은..함

. 프로그래머스 0lv 풀기_서울에 위치한 식당 목록 출력하기

SELECT INF.REST_ID, INF.REST_NAME, INF.FOOD_TYPE, INF.FAVORITES, INF.ADDRESS, ROUND(AVG(REVIEW_SCORE), 2) AS SCORE  FROM REST_INFO INF
JOIN REST_REVIEW REV
ON REV.REST_ID = INF.REST_ID
WHERE INF.ADDRESS LIKE "서울%"
GROUP BY INF.REST_ID
ORDER BY SCORE DESC, INF.FAVORITES DESC

. opic 영상 1시간 보기_✔️

. https://school.programmers.co.kr/learn/courses/2/lessons/292 여기서 부터 다시 시작_✔️

. 이것이 진도 나가기_✔️

 

tomorrow wish list

. https://school.programmers.co.kr/learn/courses/2/lessons/325 여기서부터 다시 시작

. https://www.hackers.co.kr/?c=s_lec/lec_speak/lec_Speaking_OPIc_movies&part=opic 강의 1시간 보기

. 이것이 진도 나가기

 

728x90
반응형