항해99 TIL 9일차_051722

열공이·2022년 5월 17일
0

Python Concepts & Examples

Class Objects & Instance

Example:

'''
m1 = Monster()
m1.damage(90)
m1.status_check()
'''

class Monster():
    hp = 100
    alive = True

    def damage(self,attack):
        self.hp = self.hp - attack
        if self.hp<0:
            self.alive = False

    def status_check(self):
        if self.alive:
            print('살았다')
        else:
            print('죽었다')


class Car: 
    def __init__(self, model): 
        self.model = model 
    def Car_info(self): 
        print("Model : ", self.model)

https://www.knowledgehut.com/blog/programming/self-variabe-python-examples

How to use self in Python – explained with examples:
This article helps you acquire knowledge on the self variable in Python and its internal working in Python.

www.knowledgehut.com
Difference between self and init
self : self represents the instance of the class. By using the "self" keyword all the attributes and methods of the python class can be accessed.

Here, we declared a class Car with an instance variable self.model = model.
__init__ : "__init__" is a reserved method in python classes. It is known as a constructor in object oriented concepts. This method is called when an object is created from the class and allows the class to initialize class attributes .

https://python-course.eu/oop/object-oriented-programming.php

Attributes

"In computing, an attribute is a specification that defines a property of an object, element, or file. It may also refer to or set the specific value for a given instance of such."
-Wikipedia

We can dynamically create arbitrary new attributes for existing instances of a class. We do this by joining an arbitrary name to the instance name, separated by a dot ".". In the following example, we demonstrate this by creating an attribute for the name and the year built.

class Robot:
    pass
x = Robot()
y = Robot()
x.name = "Marvin"
x.build_year = "1979"
y.name = "Caliban"
y.build_year = "1993"
print(x.name)
Attributes can be bound to class names as well. In this case, each instance will possess this name as well. If the same name is assigned to an instance, it returns the bound class brand attribute.
class Robot(object):
    pass
x = Robot()
Robot.brand = "Kuka"
x.brand
Class vs. Object (Instance)

Type Hint
Example:

def isPalindrome(x: int) -> bool:
    """
    you need to declare types of variables, parameters, and return values of a function 
    upfront. The predefined types allow the compilers to check the code before compiling 
    and running the program.
    
    parameter x is declared as an integer (x:int) & ->bool declares that the return
    value is either True or False, a boolean datatype.
    """
    x = str(x)
    left, right = 0, len(x) - 1
    while left >= 0 and right < len(x) and left <= right:
        left += 1
        right -= 1
        if x[left] == x[right]:
            return False
    return True

https://www.daleseo.com/python-type-annotations/

List Methods (sort, reverse) & Range

Example:

# print(rangelst)하면 [3,4]가 출력된다. Meaning range(3,5) contains values from 3 to 4.
list(range(3,5)

'''
a_list = [1,2,3,4,5]
# a_list.sort(reverse=True)
a_list.reverse()
# print(b_list)
# print(a_list)
'''

'''
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
# print('Original List:', systems)

# List Reverse
systems.reverse()
b = sorted(systems)
# updated list
print('Updated List:', systems)
print('sorted List:', b)
'''

https://data-make.tistory.com/102

https://rfriend.tistory.com/330

https://velog.io/@gillog/Python-List-관련-method-정리

Linked List & ListNode

Example:

class Node:
    #Node는 divided into value and pointer
    def __init__(self, item, next=None):
        self.item = item
        self.next = next

class Stack:
    def __init__(self):
        self.top = None

    def push(self, value):
        self.top = Node(value, self.top)

    def pop(self):
        if self.top is None:
            return None

        node = self.top
        self.top = self.top.next

        return node.item

    def is_empty(self):
        return self.top is None

Here, we declared a class Node with two instance variables self.item = item and self.next = next.
So, when calling a Node class, it automatically declares two variables in the instance.

https://ybworld.tistory.com/85

https://wayhome25.github.io/cs/2017/04/17/cs-19/

https://daimhada.tistory.com/72

https://velog.io/@woga1999/파이썬으로-구현하는-링크드-리스트

Deque

The upper-bound asymptotic running time (or Big-O) for Deque is O(1). So, it is better to use Deque for solving Queue algorithm problems.

데크(deque)의 개념

보통 큐(queue)는 선입선출(FIFO) 방식으로 작동한다. 반면, 양방향 큐가 있는데 그것이 바로 데크(deque)다.

즉, 앞, 뒤 양쪽 방향에서 엘리먼트(element)를 추가하거나 제거할 수 있다.
데크는 양 끝 엘리먼트의 append와 pop이 압도적으로 빠르다.

컨테이너(container)의 양끝 엘리먼트(element)에 접근하여 삽입 또는 제거를 할 경우, 일반적인 리스트(list)가 이러한 연산에 O(n)이 소요되는 데 반해, 데크(deque)는 O(1)로 접근 가능하다.

https://leonkong.cc/posts/python-deque.html
Python - 데크(deque) 언제, 왜 사용해야 하는가?
Python의 데크(deque)에 대해 알아보고 언제, 왜 써야 하는지 살펴본다

Practice

Example:

Errors

Code:

class Node:
    #Node는 divided into value and pointer
    def __init__(self, item, next=None):
        self.item = item
        print(item)
        self.next = next
        print(next)

n = Node()
n.__init__()

Problem:
line 79, in
n = Node()
TypeError: init() missing 1 required positional argument: 'item'

Looking at why the error occurs, I realized __init__ is part of Node. So, needs to be this way: n = Node(3). Get rid of n.__init__(). The __init__() function is called automatically every time the class is being used to create a new object. Therefore, when the class is called as above (Node), __init__ will be executed automatically, meaning Node needs to get the __init__ function parameters to work.
Because of the above, when class is used to create a new object,

Application

Problem-solving! Algorithms!

profile
프로그래머가 되자! 열공!

0개의 댓글