반응형

[백준] 1002번 터렛 Turrets - PYTHON 

 

https://www.acmicpc.net/problem/1002

 

 

1002번: 터렛

각 테스트 케이스마다 류재명이 있을 수 있는 위치의 수를 출력한다. 만약 류재명이 있을 수 있는 위치의 개수가 무한대일 경우에는 -1을 출력한다.

www.acmicpc.net

문제

조규현과 백승환은 터렛에 근무하는 직원이다. 하지만 워낙 존재감이 없어서 인구수는 차지하지 않는다. 다음은 조규현과 백승환의 사진이다.

이석원은 조규현과 백승환에게 상대편 마린(류재명)의 위치를 계산하라는 명령을 내렸다. 조규현과 백승환은 각각 자신의 터렛 위치에서 현재 적까지의 거리를 계산했다.

조규현의 좌표 (x1, y1)와 백승환의 좌표 (x2, y2)가 주어지고, 조규현이 계산한 류재명과의 거리 r1과 백승환이 계산한 류재명과의 거리 r2가 주어졌을 때, 류재명이 있을 수 있는 좌표의 수를 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 다음과 같이 이루어져 있다.

한 줄에 x1, y1, r1, x2, y2, r2가 주어진다. x1, y1, x2, y2는 -10,000보다 크거나 같고, 10,000보다 작거나 같은 정수이고, r1, r2는 10,000보다 작거나 같은 자연수이다.

출력

각 테스트 케이스마다 류재명이 있을 수 있는 위치의 수를 출력한다. 만약 류재명이 있을 수 있는 위치의 개수가 무한대일 경우에는 -1을 출력한다.

예제 입력 1 복사

3
0 0 13 40 0 37
0 0 3 0 7 4
1 1 1 1 1 5

예제 출력 1 복사

2
1
0
"""_summary_
   1002번 터렛 turret https://www.acmicpc.net/problem/1002
   문제
        조규현과 백승환은 터렛에 근무하는 직원이다. 하지만 워낙 존재감이 없어서 인구수는 차지하지 않는다. 다음은 조규현과 백승환의 사진이다.
        이석원은 조규현과 백승환에게 상대편 마린(류재명)의 위치를 계산하라는 명령을 내렸다. 조규현과 백승환은 각각 자신의 터렛 위치에서 현재 적까지의 거리를 계산했다.
        조규현의 좌표 (x1, y1)와 백승환의 좌표 (x2, y2)가 주어지고, 조규현이 계산한 류재명과의 거리 r1과 백승환이 계산한 류재명과의 거리 r2가 주어졌을 때, 류재명이 있을 수 있는 좌표의 수를 출력하는 프로그램을 작성하시오.
        입력
            첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 다음과 같이 이루어져 있다.
            한 줄에 x1, y1, r1, x2, y2, r2가 주어진다. x1, y1, x2, y2는 -10,000보다 크거나 같고, 10,000보다 작거나 같은 정수이고, r1, r2는 10,000보다 작거나 같은 자연수이다.
        출력
            각 테스트 케이스마다 류재명이 있을 수 있는 위치의 수를 출력한다. 만약 류재명이 있을 수 있는 위치의 개수가 무한대일 경우에는 -1을 출력한다.
        예제 입력 1 
            3
            0 0 13 40 0 37
            0 0 3 0 7 4
            1 1 1 1 1 5
        예제 출력 1 
            2
            1
            0
            
        두 원의 중심이 동일하고, 반지름이 같다면 적이 존재할 수 있는 좌표는 무한대이다 -> -1 리턴
        두 원의 반지름의 합이 두 원의 중심사이의 거리라면 외접, 두 원의 반지름의 차가 두 원의 중심사이의 거리라면 내접한다 -> 1리턴
        두 원의 반지름의 합이 두 원의 중심사이의 거리보다 크고, 두 원의 반지름의 차가 두 원의 중심사이의 거리보다 작다면 두개의 교점 -> 2리턴
        그 외에는 교점이 없다. -> 0리턴
        
         * 네 가지 경우가 존재
        첫 번째 경우 : 두 원이 접하지 않는 경우
        두 번째 경우 : 두 원이 한 점에서 접하는 경우
        세 번째 경우 : 두 원이 두 점에서 접하는 경우
        네 번째 경우 : 두 원이 일치하는 경우
"""

# x1, y1, r1, x2, y2, r2 = map(int, input().split())

def turret(x1,y1,r1,x2,y2,r2):
    dist = pow( ( (x1-x2)**2 + (y1-y2)**2 ), 0.5 )
    temp=r1+r2
    temp2=abs(r1-r2)

    if (dist == 0) :
        if (temp2 == 0):
            return -1
        else:
            return 0
    elif (dist == temp or dist == temp2):
        return 1
    elif (temp2 < dist and dist < temp):
        return 2
    else:
        return 0

testcase = int(input())
for i in range(testcase):
    a,b,c,d,e,f = map(int, input().split())
    print(turret(a,b,c,d,e,f))
    
#=============================================================   
    

import math
num = int(input())
results = []

for i in range(num):
    x1, y1, r1, x2, y2, r2 = map(int, input().split())
    d = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) # 두 원의 중심 사이의 거리
    if x1 == x2 and y1 == y2 and r1 == r2: results.append(-1) # 교점이 무한대
    elif abs(r1 - r2) < d and r1 + r2 > d: results.append(2) # 교점이 두 개인 경우
    elif abs(r1 - r2) == d or r1 + r2 == d: results.append(1) # 접하는 경우
    else: results.append(0) # 교점이 없음

for result in results:
    print(result)
반응형
반응형

[백준] 1001번 A-B - PYTHON  https://www.acmicpc.net/problem/1001

 

1001번: A-B

두 정수 A와 B를 입력받은 다음, A-B를 출력하는 프로그램을 작성하시오.

www.acmicpc.net

문제

두 정수 A와 B를 입력받은 다음, A-B를 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 A와 B가 주어진다. (0 < A, B < 10)

출력

첫째 줄에 A-B를 출력한다.

예제 입력 1 복사

3 2

예제 출력 1 복사

1
"""_summary_
    https://www.acmicpc.net/problem/1001
    문제
    두 정수 A와 B를 입력받은 다음, A-B를 출력하는 프로그램을 작성하시오.
    입력
    첫째 줄에 A와 B가 주어진다. (0 < A, B < 10)
    출력
    첫째 줄에 A-B를 출력한다.

    예제 입력 1 
    3 2
    예제 출력 1 
    1
"""

# A, B = input("값을 입력하세요~ (ex; 3 2 ): ").split()  

A, B = input().split()
print(int(A)-int(B))
반응형
반응형

[BOJ] 1000번  A+B - PYTHON  https://www.acmicpc.net/problem/1000

"""_summary_
   두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
   https://www.acmicpc.net/problem/1000
   입력
    첫째 줄에 A와 B가 주어진다. (0 < A, B < 10)
    출력
    첫째 줄에 A+B를 출력한다.

    예제 입력 1 
    1 2
    예제 출력 1 
    3
    
    입력을 받을 때 A와 B는 같은 줄에 입력을 받아야하기 때문에
    공백을 기준으로 나눠주는 split 함수를 이용하도록 하겠습니다.
    받아온 a와 b는 문자형이기 때문에 int() 를 이용하여 정수로 바꾸어 더해주었습니다.

"""

# 아래 처럼 쓸데없이 정보를 많이 넣으면 틀렸습니다. 로 나오니 주의하자. 
# A, B = input("값을 입력하세요~ (ex; 1 2 ): ").split()  

A, B = input().split()
print(int(A)+int(B))

a, b = map(int, input().split())
print(a+b)
반응형
반응형

https://www.acmicpc.net/problem/2133

 

2133번: 타일 채우기

3×N 크기의 벽을 2×1, 1×2 크기의 타일로 채우는 경우의 수를 구해보자.

www.acmicpc.net

문제

3×N 크기의 벽을 2×1, 1×2 크기의 타일로 채우는 경우의 수를 구해보자.

입력

첫째 줄에 N(1 ≤ N ≤ 30)이 주어진다.

출력

첫째 줄에 경우의 수를 출력한다.

 

예제 입력 1 복사

2

예제 출력 1 복사

3
"""_summary_
    타일 채우기 
    https://www.acmicpc.net/problem/2133
    문제 3×N 크기의 벽을 2×1, 1×2 크기의 타일로 채우는 경우의 수를 구해보자.
    입력 첫째 줄에 N(1 ≤ N ≤ 30)이 주어진다.
"""
n = int(input("값을 입력하세요~ : "))
tile = [0 for _ in range(31)]
tile[2] = 3
for i in range(4, n+1):
    if i%2 == 0:
        tile[i] = tile[i-2] * 3 + sum(tile[:i-2]) * 2 + 2
    else:
        tile[i] = 0

print(tile[n])




#2번째 풀이 

n = int(input())
dp = [0]*(n+1)

if n % 2 != 0:
    print(0)
else:
    dp[2] = 3
    for i in range(4, n+1, 2):
        dp[i] = dp[i-2] * 3 + 2
        for j in range(2, i-2, 2):
            dp[i] += dp[j] * 2

    print(dp[n])
반응형
반응형

[python] Python 3.11: 진정으로 즐길 수 있는 새로운 기능

https://towardsdatascience.com/python-3-11-new-features-that-you-will-truly-enjoy-9fd67882fdf

 

Python 3.11 New Features That You Will Truly Enjoy

Kudos to all the effort by volunteers across the world

towardsdatascience.com

이미지 출처: Unsplash

Python 3.11은 2022년 10월 24일에 출시되어 우리가 만져볼 수 있는 몇 가지 흥미로운 개선 사항을 제공했습니다. 여기에서 모든 PEP 의 전체 문서를 볼 수 있습니다 . 이 기사에서는 5가지와 추가로 여러분이 높이 평가할 멋진 새 기능을 제공할 것입니다.

PEP 657 : 오류 추적 로케이터

Python 3.11 이전에는 예외가 발생했을 때 오류 추적의 유일한 정보는 오류가 무엇인지 설명 하는 줄 이었습니다. 예를 들어,

x, y, z = 1 , 2 , 0
 a, b, c = 3 , 4 , 5
 결과 = (x / y / z) * (a / b / c)

이 코드는 0과 같은 나누기 때문에 오류를 발생시킵니다. X/Y by Z다음은 이치에 맞는 오류 메시지이지만 코드의 어느 부분이 이 문제를 일으켰는지 아직 모르기 때문에 정보가 아닙니다.

Python 3.11에서 우리는 이것을 보게 될 것입니다.

오류 탐지기의 도움으로 근본 원인이 Y 또는 Z가 0~~^~~ 이라는 것이 분명합니다 . 이 주석이 달린 트레이스백은 코드가 복잡해지면 더욱 강력해집니다.

PEP 673 : 자아 유형

유형 힌트의 경우 이전에는 현재 클래스 자체를 참조해야 하는 경우 아래와 같이 유형 변수 를 명시적으로 정의해야 했습니다.

이제 3.11에서는 Self 캡슐화 클래스 자체를 참조하는 유형을 사용할 수 있습니다. 이렇게 하면 유형 변수를 정의하는 번거로움이 사라집니다.

향상된 {asyncio} : 비동기 컨텍스트 관리자

비동기 프로그래밍을 사용하면 코드는 여전히 한 번에 한 단계씩 실행되지만 시스템은 다음 단계로 이동하기 전에 이 단계가 완료될 때까지 기다리지 않습니다.

파이썬에서 이것은 {asyncio}모듈에 의해 처리됩니다. 우리는 여러 비동기 작업을 생성하고 각 작업이 실행될 때까지 기다린 다음 asyncio.gather(). 예를 들어 심부름을 해보자.

 

터미널에서 실행하면 다음과 같은 결과가 나타납니다.

그러나 list 작업을 기다리기 전에 수동으로 모니터링하는 asyncio.gather것은 번거롭습니다. 새로운 기능/클래스 TaskGroup()가 3.11에 도입되었습니다.

 

TaskGroup종료 시 모든 작업을 기다리는 작업 그룹을 보유하는 컨텍스트 관리자로 기능합니다 . 또한 구문이 더 간단합니다.

PEP 654 : 예외 그룹

예외 처리를 위한 유사한 "그룹화" 기능은 3.11에 추가된 예외 그룹 입니다. 단일 예외에 래핑된 여러 일반 예외로 생각할 수 있습니다.

볼 수 있듯이 오류가 를 트리거하면 ExceptionGroup자체 패널에 표시된 두 하위 예외가 모두 발생했습니다.

처리 하기 위해 ExceptionGroup Python 3.11에는 새 키워드도 추가되었습니다 except*.

를 사용하면 except*에 래핑된 여러 오류 ExceptionGroup 가 처리됩니다. 이 기능은 여러 비동기 작업이 함께 실행되는 { asyncio } 에서 사용될 때 더 효과적입니다.

PEP 678 : 사용자 지정 예외 사항

add_note오류 처리를 위한 또 다른 훌륭한 새 기능은 사용자 지정 메시지를 추가할 수 있는 예외 메모입니다 . 예를 들어,

보너스 PEP 659 : 더 빠른 실행 속도

존경하는 가작으로 Python 3.11은 Faster CPython 이니셔티브 덕분에 이전 버전보다 10%-60% 더 빠를 것으로 예상됩니다.

결론: Python 3.11로 업그레이드해야 합니까?

때에 따라 다르지! 개인적으로 프로젝트에 사용된 특정 라이브러리가 아직 Python 3.11과 호환되지 않을 수 있으므로 프로덕션 환경을 업그레이드하지 않도록 주의 해야 합니다.

테스트해보고 싶다면 Google colab에서 테스트하는 것이 좋습니다. 다음을 실행하여 Python 버전을 3.11로 업그레이드할 수 있습니다.

!sudo apt-get 업데이트 -y 
!sudo apt-get install python3 .11
 !sudo 업데이트 대안 --install /usr/ bin /python3 python3 /usr/ bin /python3 .7  1
 !sudo 업데이트 대안 --install / usr/ bin /python3 python3 /usr/ bin /python3 .11  2

이 기사에서는 가장 흥미로운 새 기능만 살펴보았습니다. 모든 개선 사항 및 변경 사항에 대한 공식 릴리스 문서 를 확인하십시오 .

반응형
반응형

데이터 과학자를 위한 6가지 Python 팁

https://towardsdatascience.com/top-6-python-tips-for-data-scientists-4f4a25e44d15

 

Top 6 Python Tips for Data Scientists

Practical tips and tricks from my daily analytics projects

towardsdatascience.com

 

 

### 데이터 과학자를 위한 6가지 Python 팁
### Top 6 Python Tips for Data Scientists
### https://towardsdatascience.com/top-6-python-tips-for-data-scientists-4f4a25e44d15

codeString = '''a,b = 4,5; print(f"a = {a} and b = {b}"); print(f"a+b = {a+b}")'''
exec(codeString)

print("\n\n\n")


import os
import sys

#작업하는 경로(위치)가 어디인지 확인
print(os.getcwd())


exec(open("./Project/Datascientist/myFullFileName.py").read())

print("\n\n\n")

### 각각 현재 작업 디렉토리 또는 사용자 지정 디렉토리의 모든 파일을 나열합니다.
print( os.listdir() )



"""_summary_
"""
print("\n\n\n")

### 4. Code timer as a decorator 
import time
import requests

def timerWrapper(func):
    """Code the timer"""

    def timer(*args, **kwargs):
        """Start timer"""
        start = time.perf_counter()
        
        output = func(*args, **kwargs)
        
        timeElapsed = time.perf_counter() - start
        print(f"Current function: {func.__name__}\n Run Time: {timeElapsed}")
        return output

    return timer

## Func to make a request to an user-defined url
@timerWrapper
def getArtile(url):
    return requests.get(url, allow_redirects=True)

## Monitor the runTime 
if __name__ == "__main__":
    getArtile('https://towardsdatascience.com/6-sql-tricks-every-data-scientist-should-know-f84be499aea5')
    

print("\n\n\n")
    
## 이제 다른 함수의 시간을 측정 @timeWrapper하려면 함수 앞에 the를 놓는 것뿐입니다.
@timerWrapper
def getMultiplication(num):
    for val in range(num):
        print(10**(10**val))

getMultiplication(3)

Now, let’s jump right in!

  1. Dynamic execution with exec()

Dynamic Execution (Image Source)

Scenario: You inherited a Python project from a colleague, and immediately noticed that those scripts all have a whopping 5000+ lines of code. The same chunks (of code) got copied and pasted multiple times! So, is there a more efficient option to go about code reusability?

Let’s explore the exec() function in Python. Simply put, it takes in a string or object code, and execute it as shown in this example,

 
a = 4 and b = 5
a+b = 9

Even more handy? We can use exec(open().read()) to call and execute a file within the Python interpreter. For example,

 

With this powerful one-liner, data scientists can save programs that will be reused as standalone files, and execute them whenever needed within the main program. No code copying and pasting any more!

Being a cool functionality in Python, exec() has one pitfall to avoid — it does NOT return any value,

 
a = 4 and b = 5
a+b = 9
** Is the return from exec() is None? True **

As we can see, the output of the exec() function is None; hence, it cannot be used to store any values, which is equivalent to the sounce()function in R.

***Join our YouTube community 🎦 “Data Talks with Kat” 😄

 

2. Operating system commands with {os} and {shutil}

Scenario: continue from our previous tip, now you want to check out the script before executing it. Don’t bother to double-click your mouse all the way through to open up the file? No problem, you can easily achieve this in Python directly without interrupting your train of thought.

 

Here, the os.startfile() function allows users to open up any type of files, including MS documents, Excels, R and SQL scripts.

Similarly, we can also delete a FILE using os.remove(“myFullFileName.ANYFORMAT”)

or delete the entire DIRECTORY using shutil.rmtree(“folderToBeRemoved”). where {shutil} is a Python module that offers a number of high-level file operations, particularly for file copying and removal.

Therefore, if you haven’t used {os} other than os.getcwd() or os.chdir() or if the {shutil} sounds unfamiliar, it’s time to check out their documents. You will definitely find useful commands or file system methods that make your coding easier. Here lists a few of my favorites,

  • os.listdir() or os.listdir(“someDirectory”) — list all files in the currently working directory or any user-specified directory, respectively;
  • os.path.join() — automatically create a path with elements in the arguments for later use, e.g., os.path.join(‘D’, ‘Medium’, ‘New Folder’) will return
 ‘D\\Medium\\New Folder’
  • os.makedirs() — create a directory;
  • shutil.copy2(“sourcePath”, “destinationPath”) or shutil.move(“sourcePath”, “destinationPath”) — copy or cut a file respectively.

3. One-liner: Nested list comprehension to get rid of the for loops

Scenario: this “simple” task we come across is to combine several lists into one big long list,

 

Surely, we can write five nested for loops to append each sublist to the final output list. But it’s smarter to turn to nested list comprehension for the most concise way,

 

4. Timer wrapped as a decorator

Timer as a decorator (Image Source)

Scenario: while Python is recognized as one of the most effective programming languages, data scientists still need to check the runtime of our programs.

It’s not the hardest thing if we just implement a bare-bones Python timer for each function we want to monitor. However, if we code it as a decorator, we would make our timer much easier to be version-controlled and reused!

Here is how,

 

In this snippet,

  • the timer is wrapped in a timerWrapper function, which then is used as a decorator called prior to the main function;
  • The example main function is to return a request connecting to an URL, which is one of my previous blogs.

Running this code gives us the time elapsed,

Current function: getArtile
 Run Time: 1.6542516000008618Out[101]: <Response [200]>

Now, to time another function, all we need is to put the @timeWrapper in front of the function,

 
getMultiplication(3)
10
10000000000
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Current function: getMultiplication
 Run Time: 0.00014700000065204222

5. Leverage the options system to customize your display

Scenario: as data scientists, we analyze data with {pandas} and {numpy} on a daily basis. When I first learned coding in Python, I was frustrated seeing this after reading my data into the IDE,

Clearly, data display is cut off both row-wise and column-wise, and the following code can fix it,

 

Here, we are explicitly setting the maximum columns, rows and column width to display/print in the console. There are numerous customizable options and settings in {pandas}, and similar operations are also available in {numpy} for arrays and matrix,

 

6. Reproduce your machine learning model results? Set seeds!

Scenario: Due to the stochastic nature of machine learning modeling process, we have all encountered the non-deterministic aspect of machine learning. This randomness results in our difficulty reproducing the same results across different runs. Consequently, it’s challenging to figure out whether an improvement in performance metrics is a result of successful model tuning or simply a different random training/testing sample.

Luckily the reproducibility can be achieved by setting the random seed throughout your model pipeline, provided that you do it correctly! How many times have you seen questions like “Getting a different result despite random seed defined” popping up on Stack Overflow? Well, how to appropriately set seeds should be in the first page of documentations, but it took me some time to dig it out.

I found that NOT every seed is defined the same in {numpy}, {sklearn}, {tensorflow} or {torch}. Thus, it’s a best practice to use a definitive function that sets all SEEDS for all your frameworks. For example,

 

Adding this tactical reset_random_seed() function to all necessary steps of your workflow, such as train-test split, model compile/training, and interpretation, will get you half way to full reproducibility. More detailed visibility into your experiments will finish the second half!

반응형
반응형

React와 Django로 웹 서비스 뚝딱 세팅하기 (feat. Webpack, Redux, django rest framework, PWA)

http://milooy.github.io/TIL/Django/react-with-django-rest-framework.html#%E1%84%86%E1%85%A9%E1%86%A8%E1%84%91%E1%85%AD

 

[서버부터 프론트까지] React와 Django로 웹 서비스 뚝딱 세팅하기 (feat. Webpack, Redux, django rest framework

[서버부터 프론트까지] React와 Django로 웹 서비스 뚝딱 세팅하기 (feat. Webpack, Redux, django rest framework, PWA) 목표 모임 개설 사이트, 'MOGAE' 제작. Django에 Django Rest Framework를 얹어 API 서버를, react로 프론

milooy.github.io

목표

모임 개설 사이트, 'MOGAE' 제작. Django에 Django Rest Framework를 얹어 API 서버를, react로 프론트엔드를 개발합니다. 상태관리는 redux로 하며 Progressive Web App기술을 적용해 앱처럼 사용할 수 있습니다.

이를 연동하여 온전한 웹 어플리케이션을 만드는 것에 초점을 맞춘 튜토리얼입니다. (기술에 대한 설명은 하지 않습니다.)

#사용 버전

  • Python: 3.4.3
  • Django: 1.11.3
  • Django Rest Framework: 3.6.3

장고걸스 : https://tutorial.djangogirls.org/ko/django_installation/

 

Django 설치하기 · HonKit

virtualenv를 생성하려면 콘솔 창을 열고, (이전 장에서 얘기했는데, 기억나죠?) 그리고 C:\Python35\python -m venv myvenv를 실행하세요. 아마도 화면에 이렇게 보일 거에요. : command-line C:\Users\Name\djangogirls>

tutorial.djangogirls.org

https://gitter.im/DjangoGirls/tutorial

 

DjangoGirls/tutorial

This is a tutorial we are using for Django Girls workshops

gitter.im

 

@ Django 자습 : https://wikidocs.net/book/837

 

Django 자습

Django 자습, 요약, 정리 # 출처 ## 참고 서적 * Django로 배우는 쉽고 빠른 웹 개발 - 파이썬 웹 프로그래밍 * Django를 활용한 쉽고 빠른 웹 …

wikidocs.net

 

반응형
반응형

변수는 프로그래밍에서 "하나의 데이터(숫자, 문자등)를 저장할 수 있는 메모리 공간"으로, 데이터 타입에 따라 정수, 소수, 문자등을 저장할 수 있다.

변수의 이름을 정의함에 있어 일반적인 룰은 아래와 같다. 

- 파이썬에서 예약어는 사용할 수 없다.

- 변수는 하나의 문자(a letter)나 밑줄(underscore) 시작해야 한다. 

- 변수의 두번째 문자부터는 문자(letter), 숫자(number) 또는 밑줄(underscore)를 사용할 수 있다. 

- 변수는 대, 소문자을 구분한다. 

- 변수명의 타입은 값에 따라 변화한다. 

 

표준 데이터 유형

데이터 유형 할당 구분 아이템 구분 특징
숫자 Number Type      
문자 StringType "" or ''    
셋 Set Type {} , 중복제외, 순서없음
리스트 List Type [] ,  
딕셔너리 Dictionary Type {} , 키와 값으로 분리
튜플 Tuple () , 수정불가

 

 

데이터 형식 변환 (Data Type Conversion)

 

Function Description
int(x) x 값을 정수 타입으로 변환한다.
float(x) x 값을 부동 소수점 타입으로 변환한다.
complex(x) x 값을 복소수 타입으로 변환한다.
str(x) x 값을 문자 타입으로 변환한다.
repr(x) x 값을 표현식 문자 타입으로 변환한다.
eval(str) x 값이 문자 타입인지를 검증한다.
tuple(s) s를 튜플 타입으로 변환한다.
list(s) s 값을 리스트 타입으로 변환한다.
set(s) s 값을 셋 타입으로 변환한다.
dict(d) d 값을 딕셔너리 타입으로 변환한다.
frozenset(s) s 값을 고전 셋 타입으로 변환한다.
chr(x) x 값을 문자 타입으로 변환한다.
ord(x) x 값을 정수 타입으로 변환한다.
hex(x) x 값을 16진수 문자 타입으로 변환한다.
oct(x) x 값을 8진수 문자 타입으로 변환한다.

 

반응형

+ Recent posts