Program/[Kaggle] 30 Days of ML

[30 Days of ML] Day 5 - part 1

uding9 2021. 8. 8. 20:02
반응형

Tutorial


Lists

Python의 list는 [ ]로 묶어서 나타내는 ordered sequences of values임

리스트는 아래와 같이 다른 유형의 값들도 함께 포함할 수 있음

my_favourite_things = [32, 'raindrops on roses', help]

Indexing

[i]를 사용해 리스트의 원소에 접근할 수 있음


Slicing

my_list[i:j] 이런식으로 여러 개의 원소들도 접근할 수 있음


Changing lists

인덱싱을 통해 하나의 값을 변경할 수 있음

print(planets)
planets[3] = 'Malacandra'
print(planets)
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
['Mercury', 'Venus', 'Earth', 'Malacandra', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

슬라이싱을 통해 여러 개의 값을 변경할 수 있음

planets[:3] = ['Mur', 'Vee', 'Ur']
print(planets)
planets[:4] = ['Mercury', 'Venus', 'Earth', 'Mars',]
print(planets)
['Mur', 'Vee', 'Ur', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

List functions

len() : 길이

sorted() : 정렬

sum() : 합계

max() : 최댓값


Interlude: objects

파이썬의 모든 것(아마 대부분?)을 '객체(object)'라고 부를 수 있음(ex> 리스트, 튜플, ...)

파이썬의 숫자는 허수부(imaginary part)를 나타내는 imag라는 속성(attributes)를 가짐

x=12
# x 는 실수이므로 허수부는 0임
print(x.imag)

# 복소수
c = 12 + 3j
print(c.imag)
0
3.0

객체는 함수 또한 포함하며 메소드(method)라고 부름

print(x.bit_length)
print(x.bit_length())
<built-in method bit_length of int object at 0x562850c983e0>4

List methods

list.append 리스트의 마지막에 원소를 추가함

print(planets)
planets.append('Pluto')
print(planets)
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto']

list.pop은 리스트의 마지막 원소를 제거하여 반환함

planets.pop()
'Pluto'

print를 통해 확인하면 마지막 원소 'Pluto'가 제거된 것을 확인할 수 있음

print(planets)
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

Searching lists

list.index 를 통해 원소의 인덱스를 얻을 수 있음

planets.index('Earth')
2

Tuples

튜플은 리스트와 거의 동일하지만 두 가지 다른 점이 있음

  1. [ ] 대신 ( ) 를 사용하여 생성
t = (4, 5, 6)
t = 4, 5, 6
print(t)
(4, 5, 6)
  1. 수정할 수 없음
t[0] = 100
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-e6cf7836e708> in <module>
----> 1 t[0] = 100

TypeError: 'tuple' object does not support item assignment

튜플은 여러 반환 값이 있는 함수에 자주 사용됨

예를 들어, float 객체의 as_integer_ratio() 메소드는 튜플 형태로 분자와 분모를 반환함

x = 0.125
x.as_integer_ratio()
(1, 8)

swap 대신 다음과 같이 swapping 할 수 있음

a, b = 1, 0
print(a, b)
a, b = b, a
print(a, b)
1 0
0 1

Exercise

5.

내 코드

def fashionably_late(arrivals, name):
    """Given an ordered list of arrivals to the party and a name, return whether the guest with that
    name was fashionably late.
    """    
    a = int(len(arrivals)/2) if len(arrivals)/2 == len(arrivals)//2 else len(arrivals)//2+1
    if name in arrivals[a:-1]:
        return True
    else:
        return False

답 코드

def fashionably_late(arrivals, name):
    """Given an ordered list of arrivals to the party and a name, return whether the guest with that
    name was fashionably late.
    """
    idx = arrivals.index(name)
    # 절반 이상 후에 도착 & 마지막 x
    return idx>=len(arrivals)/2 and idx != len(arrivals)-1

조건만 잘 생각하면 정답 코드와 같이 한 줄로 해결할 수 있는 문제

반응형